求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
说明
什么是逆波兰表达式?
http://en.wikipedia.org/wiki/Reverse_Polish_notation
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
if(null == tokens || tokens.length == 0) return 0;
Set<String> cSet = new HashSet<String>();
cSet.add("+");
cSet.add("-");
cSet.add("*");
cSet.add("/");
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < tokens.length; i++) {
if(!cSet.contains(tokens[i])) {
stack.push(Integer.valueOf(tokens[i]));
}else {
int b = stack.pop();
int a = stack.pop();
int c = 0;
char[] arr = tokens[i].toCharArray();
switch (arr[0]){
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
}
stack.push(c);
}
}
return stack.peek();
}
}