Monday, February 3, 2014

Leetcode: 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

Solution:

    public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens == null)
            return 0;
        ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
        for(int i=0; i<tokens.length; i++)
        {
            if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))
            {
                int operand2 = stack.pop();
                int operand1 = stack.pop();
                switch(tokens[i].charAt(0))
                {
                    case '+': stack.push(operand1+operand2); break;
                    case '-': stack.push(operand1-operand2); break;
                    case '*': stack.push(operand1*operand2); break;
                    case '/': stack.push(operand1/operand2); break;
                }
            }
            else
            {
                int value = Integer.parseInt(tokens[i]);
                stack.push(value);
            }
        }
        return stack.pop();
    }
}

No comments :

Post a Comment