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

LeetCode-Evaluate Reverse Polish Notation

2015-10-01 08:38 441 查看
因为是很标准的两个oprand 一个operator 所以很简单 

但是注意string compare不能用==!!!要用equals

外加注意-和/的顺序

public class Solution {
public int evalRPN(String[] tokens) {
Stack <Integer> stack = new Stack <Integer> ();
for ( int i = 0; i < tokens.length; i ++ ){
if ( tokens[i].equals("+")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 + op2);
}
else if ( tokens[i].equals("-") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 - op1);
}
else if ( tokens[i].equals("*")){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op1 * op2);
}
else if ( tokens[i].equals("/") ){
int op1 = stack.pop();
int op2 = stack.pop();
stack.push(op2 / op1);
}
else{
stack.push( Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: