Linkedin Medium
这道题用Stack of Integer要方便得多,用Stack of string则要来回转换。
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();
}
}