Evaluate Reverse Polish Notation 424

Question

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

Solution

完全按照RPN的定义即可。具体过程wikipedia上说的非常清楚。

例子:

5 1 2 + 4 × + 3 −

代码如下:

public class Solution {
    /**
     * @param tokens The Reverse Polish Notation
     * @return the value
     */
    public int evalRPN(String[] tokens) {
        // Write your code here
        if(tokens == null || tokens.length == 0){
            return 0;
        }

        Stack<Integer> stack = new Stack<Integer>();

        for(int i = 0; i < tokens.length; i++){
            if("+-*/".contains(tokens[i])){
                // if(stack.size() < 2){
                //     return -1;
                // }
                int a = stack.pop();
                int b = stack.pop();
                if(tokens[i].equals("+")){
                    stack.push(b + a);
                }
                if(tokens[i].equals("-")){
                    stack.push(b - a);
                }
                if(tokens[i].equals("*")){
                    stack.push(b * a);
                }
                if(tokens[i].equals("/")){
                    stack.push(b / a);
                }
            }else{
                stack.push(Integer.valueOf(tokens[i]));
            }
        }

        return stack.pop();
    }
}

results matching ""

    No results matching ""