题目
题目链接:https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
核心
栈
参考答案C++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串vector
* @return int整型
*/
int evalRPN(vector<string>& tokens) {
//栈。vector模拟
vector<int> stack(tokens.size());
int idx = 0;
for(int i=0;i< tokens.size();i++){
string s = tokens[i];
if(s=="+" || s=="-" || s== "*" || s=="/"){
int num1 = stack[idx-1];
int num2 = stack[idx-2];
int cur = 0;
if(s=="+"){
cur = num2+num1;
}
if(s=="-"){
cur = num2-num1;
}
if(s=="*"){
cur = num2*num1;
}
if(s=="/"){
cur = num2/num1;
}
stack[idx-2] = cur;
idx-=1;
}else{
stack[idx++] = std::stoi(s);
}
}
return stack[idx-1];
}
};
参考答案Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int evalRPN (String[] tokens) {
//栈
List<String> strings = Arrays.asList("+", "-", "*", "/");
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (strings.contains(s)) {
compute(stack, s);
} else {
stack.add(Integer.valueOf(s));
}
}
return stack.pop();
}
public void compute(Stack<Integer> stack, String op) {
int num1 = stack.pop();
int num2 = stack.pop();
int ans = 0;
if (op.equals("+"))
ans = num2 + num1;
if (op.equals("-"))
ans = num2 - num1;
if (op.equals("*"))
ans = num2 * num1;
if (op.equals("/"))
ans = num2 / num1;
stack.add(ans);
}
}
参考答案Go
package main
import "strconv"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
func evalRPN(tokens []string) int {
//栈。本答案数组模拟栈
stack := make([]int, len(tokens))
idx := 0
for i := 0; i < len(tokens); i++ {
s := tokens[i]
if s == "+" || s == "-" || s == "*" || s == "/" {
//每次从栈中取出栈顶的2个数,计算结果后存进栈中
num1 := stack[idx-1]
num2 := stack[idx-2]
cur := 0
if s == "+" {
cur = num2 + num1
}
if s == "-" {
cur = num2 - num1
}
if s == "*" {
cur = num2 * num1
}
if s == "/" {
cur = num2 / num1
}
idx -= 2
stack[idx] = cur
idx += 1
} else {
num, _ := strconv.Atoi(s)
stack[idx] = num
idx++
//fmt.Println(stack)
}
}
return stack[idx-1]
}
参考答案PHP
<?php
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
function evalRPN( $tokens )
{
// PHP中数组也是栈。本答案用数组模拟栈
$stack =[];
$idx = 0;
for($i=0;$i<count($tokens);$i++){
$s= $tokens[$i];
if($s =='+' || $s == '-' || $s =='*' || $s =='/'){
//取出栈顶2个数计算结果后存入栈中
$num1 = $stack[$idx-1];
$num2 = $stack[$idx-2];
$cur = 0;
if($s =='+') {
$cur = $num2+$num1;
}
if($s =='-') {
$cur = $num2-$num1;
}
if($s =='*') {
$cur = $num2*$num1;
}
if($s =='/') {
$cur =intval( $num2/$num1);
}
$stack[$idx-2] = $cur;
$idx-=1;
}else{
$stack[$idx++] = $s;
}
}
return $stack[$idx-1];
}