Evaluate Reverse Polish Notation

自己裸写,一遍过,牛!
搜了一下,别人跟我写的差不多,还有讲解: 戳参考链接

public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> s = new Stack<String>();
for(int i = 0; i < tokens.length; i++) {
if(!isOperator(tokens[i])) {
s.push(tokens[i]);
} else {
int first = Integer.parseInt(s.pop());
int second = Integer.parseInt(s.pop());
s.push(String.valueOf(compute(first, second, tokens[i])));
}
}
return Integer.parseInt(s.pop());
}

private boolean isOperator(String s) {
if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) return true;
return false;
}

private int compute(int first, int second, String operator) {
if(operator.equals("+")) return first + second;
if(operator.equals("-")) return second - first;
if(operator.equals("*")) return first * second;
return second / first;
}
}


posted @ 2014-12-30 10:25  江南第一少  阅读(100)  评论(0)    收藏  举报