Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 150] Evaluate Reverse Polish Notation

Question

link

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

Stats

Adjusted Difficulty 2
Time to use --------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a classic question. It’s easy.

Code

my code

public int evalRPN(String[] tokens) {
    if (tokens == null || tokens.length == 0)
        return 0;
    Stack<Integer> stack = new Stack<Integer>();
    for (int p = 0; p < tokens.length; p ++) {
        char cur = tokens[p].charAt(0);
        if (cur >= '0' && cur <= '9' 
                || tokens[p].length() > 1)
            stack.push(Integer.parseInt(tokens[p]));
        else if (cur == '+') {
            int num1 = stack.pop();
            int num2 = stack.pop();
            stack.push(num1 + num2);
        }
        else if (cur == '-') {
            int num1 = stack.pop();
            int num2 = stack.pop();
            stack.push(num2 - num1);
        }
        else if (cur == '*') {
            int num1 = stack.pop();
            int num2 = stack.pop();
            stack.push(num1 * num2);
        }
        else if (cur == '/') {
            int num1 = stack.pop();
            int num2 = stack.pop();
            stack.push(num2 / num1);
        }
    }
    return stack.pop();
}