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 class Solution {
private Set<String> set = new HashSet<String>();
{ //初始化块
set.add("+");
set.add("-");
set.add("*");
set.add("/");
}
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
int num1,num2 = 0;
for(int i=0;i<tokens.length;i++) {
if(!set.contains(tokens[i])) {
stack.push(Integer.parseInt(tokens[i]));
} else {
num2 = stack.pop();
num1 = stack.pop();
stack.push(calculate(tokens[i].charAt(0), num1, num2));
}
}
return stack.pop();
}
private int calculate(char operator, int num1, int num2) {
switch(operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
}