Medium
这个Wikipedia的解释非常Helpful, 尤其下面那种讲清楚栈里面有什么的那张图表.
Reverse Polish notation
我的写法比较straightforward了,但是我居然忘记了如何判断String是不是valid integer的方法了,所以先把其他情况穷举完了.
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens){
if (token.equals("+")){
int num1 = stack.pop();
int num2 = stack.pop();
int sum = num1 + num2;
stack.push(sum);
} else if (token.equals("-")){
int num1 = stack.pop();
int num2 = stack.pop();
int subs = num2 - num1;
stack.push(subs);
} else if (token.equals("*")){
int num1 = stack.pop();
int num2 = stack.pop();
int prod = num1 * num2;
stack.push(prod);
} else if (token.equals("/")){
int num1 = stack.pop();
int num2 = stack.pop();
int quot = num2 / num1;
stack.push(quot);
} else {
int num = Integer.parseInt(token);
stack.push(num);
}
}
return stack.pop();
}
}