[LintCode] Evaluate Reverse Polish Notation

Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Example

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Note

Switch中的运算符case,运算之后要break出来,继续遍历tokens数组。
default是放入新的数字,用parseInt()/valueOf()转换String为Integer均可。

Solution

public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length % 2 == 0) return 0;
        Stack stack = new Stack();
        for (String tok: tokens) {
            switch(tok) {
                case "+": 
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    stack.push(-stack.pop() + stack.pop());
                    break;
                case "*":
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    int divisor = stack.pop();
                    int dividend = stack.pop();
                    stack.push(dividend/divisor);
                    break;
                default:
                    stack.push(Integer.valueOf(tok));
            }
        }
        return stack.pop();
    }
}

你可能感兴趣的:(java,stack,switch语句)