您的位置:首页 > 编程语言 > Lua

150. Evaluate Reverse Polish Notation

2016-09-14 12:56 405 查看
跟符号还有运算顺序有关的基本就是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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: