150. Evaluate Reverse Polish Notation
跟符号还有运算顺序有关的基本就是STACK来做。
里面类型Sring或者Integer都可以,但是免不了来回转换。
public class Solution {
public int evalRPN(String[] tokens)
{
if(tokens.length == 0) return 0;
Stack<String> stk = new Stack<>();
for(int i = 0; i < tokens.length;i++)
{
String str = tokens[i];
if(str.length() > 1 || (str.charAt(0) >= '0' && str.charAt(0) <= '9'))
{
stk.push(str);
}
else
{
int b = Integer.valueOf(stk.pop());
int a = Integer.valueOf(stk.pop());
char c = str.charAt(0);
int res = 0;
if(c == '+') res = a+b;
else if ( c == '-') res = a -b;
else if( c == '*') res = a*b;
else res = a/b;
stk.push(Integer.toString(res));
}
}
return Integer.valueOf(stk.pop());
}
}