2014年2月11日星期二

LeetCoder - Evaluate Reverse Polish Notation

 Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:


  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stk = new Stack<Integer>();
        HashSet<String> ops = new HashSet<String>(Arrays.asList("+", "-", "*", "/"));
        for(int i=0;i<tokens.length;i++) {
            String tk = tokens[i];
            if(ops.contains(tk)) {
                int n1 = stk.pop();
                int n2 = stk.pop();
                int n = 0;
                if(tk.equals("+")) {
                    n = n1 + n2;
                } else if(tk.equals("-")) {
                    n = n2 - n1;
                } else if(tk.equals("*")) {
                    n = n2 * n1;
                } else if(tk.equals("/")) {
                    n = n2 / n1;
                }
                stk.push(n);
            } else {
                stk.push(Integer.parseInt(tk));
            }
        }
        return (int)stk.pop().intValue();
    }
}

没有评论:

发表评论