Description
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
问题描述
计算逆波兰表达式的值。
有效的操作符为 + , -, *, 或者 / .每个操作数为整数或者一个表达式的值
问题分析
如果对逆波兰表达式求值和如何产生后缀表达式如熟悉的话,可以看看这两篇文章
如何产生后缀表达式
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
逆波兰表达式求值
https://en.wikipedia.org/wiki/Reverse_Polish_notation
解法2有点特殊,递归处理逆序遍历
解法1(迭代)
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(String str : tokens){
if(str.equals("+")){
int num = stack.pop();
stack.push(stack.pop() + num);
}else if(str.equals("-")){
int num = stack.pop();
stack.push(stack.pop() - num);
}else if(str.equals("*")){
int num = stack.pop();
stack.push(stack.pop() * num);
}else if(str.equals("/")){
int num = stack.pop();
stack.push(stack.pop() / num);
}else{
stack.push(Integer.valueOf(str));
}
}
return stack.pop();
}
}
解法2(递归)
class Solution {
private int curr;
public int evalRPN(String[] tokens) {
curr = tokens.length - 1;
return eval(tokens);
}
private int eval(String[] tokens) {
String token = tokens[curr--];
char c = token.charAt(0);
if (token.length() == 1 && isOp(c)) {
int b = eval(tokens);
int a = eval(tokens);
return applyOp(c, a, b);
} else {
return Integer.parseInt(token);
}
}
private boolean isOp(char c) {
switch (c) {
case '+': case '-': case '*': case '/': return true;
}
return false;
}
private int applyOp(char op, int a, int b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return a;
}
}