适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for(String s : tokens){
if(s.equals("+")){
int a = stack.pop();
int b = stack.pop();
stack.push(b + a);
} else if(s.equals("-")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b - a);
} else if (s.equals("/")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
} else if (s.equals("*")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b * a);
} else {
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
}