求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +
, -
, *
, /
。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
题目其实就是语法树后序遍历的结果
TC = O(n)
SC = O(m),m表示叶子数目,即数字的个数,当左子树全是数字,栈的SC值达到最大
public class Solution {
/*
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
public int evalRPN(String[] tokens) {
// write your code here
Stack<Integer> stack = new Stack<Integer>();
int n = tokens.length;
//double res=0;
for(int i=0; i<n; i++){
String s = tokens[i];
if(s.charAt(s.length()-1)>='0' && s.charAt(s.length()-1)<='9'){
stack.push(Integer.valueOf(s));
}else{
Integer b = stack.pop();
Integer a = stack.pop();
switch(s.charAt(0)){
case '*':
stack.push(a*b);
break;
case '+':
stack.push(a+b);
break;
case '-':
stack.push(a-b);
break;
case '/':
stack.push(a/b);
break;
}
}
}
return stack.pop();
}
}