Saturday, July 11, 2015

Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

25%
Accepted
Evaluate the value of an arithmetic expression inReverse Polish Notation.
Valid operators are +-*/. Each operand may be an integer or another expression.
Have you met this question in a real interview? 
Yes
Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
public class Solution {
    /**
     * @param tokens The Reverse Polish Notation
     * @return the value
     */
    public int evalRPN(String[] tokens) {
        // Write your code here
        Stack<Integer> stack = new Stack<Integer>();
        String operators = "+-/*";
        for(String token : tokens){
            if(!operators.contains(token)){
                stack.push(Integer.parseInt(token));
            } else {
                int b = stack.pop();
                int a = stack.pop();
                switch(token){
                   case "+" : stack.push(a + b); break;
                    case "-" : stack.push(a - b); break;
                    case "*" : stack.push(a * b); break;
                    case "/" : stack.push(a / b); break;
                }
            }
        }
        return stack.pop();
    }
}


No comments:

Post a Comment