Question
150. Evaluate Reverse Polish Notation
Solution
2 1 + 3 *
是((2+1)*3)
的后缀(postfix)或逆波兰(reverse Polish)记法,计算这个表达式容易想到栈,当见到一个数时就入栈,见到操作符时该运算符作用于从该栈中弹出的两个数上,将所得结果入栈。
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String tmp : tokens) {
if (tmp.length() > 1) {
stack.push(Integer.parseInt(tmp));
continue;
}
char c = tmp.charAt(0); // String转char
int a, b;
switch (c) {
case '+':
b = stack.pop();
a = stack.pop();
stack.push(a + b);
break;
case '-':
b = stack.pop();
a = stack.pop();
stack.push(a - b);
break;
case '*':
b = stack.pop();
a = stack.pop();
stack.push(a * b);
break;
case '/':
b = stack.pop();
a = stack.pop();
stack.push(a / b);
break;
default:
stack.push(c - '0'); // char 转 int
}
}
return stack.pop();
}