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

150. Evaluate Reverse Polish Notation

2016-08-13 17:20 344 查看
实现这个 xxx   运算符在后  数值在前的 表达方式

用栈实现,编译通过  提交提示最后return的一句 为空栈异常。尴尬。。

把== 换成equals() 就不空栈异常了

public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<>();
int num1;int num2;
for(int i=0;i<tokens.length;i++){
if(!(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")))
stack.push(Integer.parseInt(tokens[i]));
else{
num2=stack.pop();
num1=stack.pop();
if(tokens[i]=="+"){
stack.push(num1+num2);
}
if(tokens[i]=="-"){
stack.push(num1-num2);
}
if(tokens[i]=="*"){
stack.push(num1*num2);
}
if(tokens[i]=="/"){
stack.push(num1/num2);
}
}
}
return stack.pop();
}

找到discuss代码  稍简单一些
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: