思路:栈
非常基础的题目,唯一需要注意的就是操作数的顺序以及switch中可以放String类型(jdk7开始)
class Solution {
boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}
public int evalRPN(String[] tokens) {
Stack<Integer> nums = new Stack<>();
for (String str : tokens) {
if (!isOperator(str)) {
nums.push(Integer.parseInt(str));
} else {
int result = 0, num1 = nums.pop(), num2 = nums.pop();
switch (str) {
case "+":
result = num2 + num1;
break;
case "-":
result = num2 - num1;
break;
case "*":
result = num2 * num1;
break;
case "/":
result = num2 / num1;
break;
}
nums.push(result);
}
}
return nums.pop();
}
}
Go代码
func evalRPN(tokens []string) int {
var stack []int
for _, token := range tokens {
if num, err := strconv.Atoi(token); err == nil {
stack = append(stack,num)
} else {
length := len(stack)
num1, num2 := stack[length-2], stack[length-1]
stack = stack[0 : length-2]
switch token {
case "+":
stack = append(stack, num1+num2)
case "-":
stack = append(stack, num1-num2)
case "*":
stack = append(stack, num1*num2)
case "/":
stack = append(stack, num1/num2)
}
}
}
return stack[0]
}