Thursday, December 11, 2014

Evaluate Reverse Polish Notation LeetCode

Use stack to contain all the values. When we get the operators, we pop up two values for operation.

It's easy. It has lots of follow up question.


public int evalRPN(String[] tokens) {
        if (tokens==null || tokens.length == 0) return 0;
        if (tokens.length == 1) return Integer.valueOf(tokens[0]);
       
        Stack<String> stack = new Stack<String>();
        String operators = "+-*/";
       
        for (int i=0; i<tokens.length; i++) {
            if (!operators.contains(tokens[i])) {
                stack.push(tokens[i]);
            } else {
                int a = Integer.valueOf(stack.pop());
                int b = Integer.valueOf(stack.pop());
               
                switch(tokens[i]) {
                    case "+" : stack.push(String.valueOf(a+b)); break;
                    case "-" : stack.push(String.valueOf(b-a)); break;
                    case "*" : stack.push(String.valueOf(a*b)); break;
                    case "/" : stack.push(String.valueOf(b/a)); break;
                }
            }
        }
        return Integer.valueOf(stack.pop());
    }

No comments:

Post a Comment