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;
}
}

浙公网安备 33010602011771号