Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Have you met this question in a real interview?
思路: 逆波兰式, 逻辑上肯定是要用 stack 的。
易错点: 注意 stack 出栈顺序是反着的。 因此 减和除的时候要注意。
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens.length < 1)
return 0;
Stack<Integer> s = new Stack<Integer>();
for(int i = 0; i < tokens.length; i++){
if(tokens[i].equals("+")){
int b = s.pop();
int a = s.pop();
s.push(a + b);
}else if(tokens[i].equals("-")){
int b = s.pop();
int a = s.pop();
s.push(a - b);
}else if(tokens[i].equals("*")){
int b = s.pop();
int a = s.pop();
s.push(a * b);
}else if(tokens[i].equals("/")){
int b = s.pop();
int a = s.pop();
s.push(a / b);
}else{
s.push(Integer.parseInt(tokens[i]));
}
}
return s.pop();
}
}