150. Evaluate Reverse Polish Notation
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
从左到右遍历表达式的每个数字和字符,遇到数字就进栈,遇到符号,就将栈顶的两个数字取出(注意第一次取出的是右操作数,第二次取出的栈顶数字是左操作数),进行运算,将运算结果压栈,一直到最终获得计算结果(最终的栈顶数字)。
逆波兰式求值(后缀表达式)
public int evalRPN(String[] tokens) {
int len;
if ((len = tokens.length) == 0)
return 0;
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < len; i++) {
try {
int tmp = Integer.valueOf(tokens[i]);
stk.push(tmp);
} catch (Exception e) {
// 栈的弹出顺序,先弹后面
int sec = stk.pop();
// 处理一个数字是负数的情况如{"3", "-" }
// 或者 { "6", "3", "*", "-" }
int fir = 0;
if (!stk.isEmpty())
fir = stk.pop();
int tmp = 0;
if (tokens[i].equals("+"))
tmp = fir + sec;
if (tokens[i].equals("-"))
tmp = fir - sec;
if (tokens[i].equals("*"))
tmp = fir * sec;
if (tokens[i].equals("/"))
tmp = fir / sec;
stk.push(tmp);
}
}
return stk.pop();
}