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

150. Evaluate Reverse Polish Notation

2018-03-19 00:27 246 查看

该方法使用栈来解决。
public class Solution {
    public int evalRPN(String[] tokens) {
        int a,b;
Stack<Integer> S = new Stack<Integer>();
for (String s : tokens) {
if(s.equals("+")) {
S.add(S.pop()+S.pop());
}
else if(s.equals("/")) {
b = S.pop();
a = S.pop();
S.add(a / b);
}
else if(s.equals("*")) {
S.add(S.pop() * S.pop());
}
else if(s.equals("-")) {
b = S.pop();
a = S.pop();
S.add(a - b);
}
else {
S.add(Integer.parseInt(s));
}
}
return S.pop();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: