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

Java

public class Solution {
    public interface Operator {
        public int eval(int x, int y);
    }
    private static final Map<String, Operator> OPERATORS;
    static {
        Map<String, Operator> map = new HashMap<String, Operator>();

        map.put("+", new Operator() {
            public int eval(int x, int y) {
                return x + y;
            }
        });
        map.put("-", new Operator() {
            public int eval(int x, int y) {
                return x - y;
            }
        });
        map.put("*", new Operator() {
            public int eval(int x, int y) {
                return x * y;
            }
        });
        map.put("/", new Operator() {
            public int eval(int x, int y) {
                return x / y;
            }
        });

        OPERATORS = Collections.unmodifiableMap(map);
    }

    public int evalRPN(String[] tokens) {
        Stack<Integer> val = new Stack<Integer>();
        for(String token : tokens) {
            if(OPERATORS.containsKey(token)) {
                int y = val.pop();
                int x = val.pop();
                val.push(OPERATORS.get(token).eval(x, y));
            } else {
                val.push(Integer.parseInt(token));
            }
        }
        return val.pop();
    }
}