lintcode-medium-Evaluate Reverse Polish Notation

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Evaluate Reverse Polish Notation相关的知识,希望对你有一定的参考价值。

Evaluate the value of an arithmetic expression inReverse Polish Notation.

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

 

["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
        
        if(tokens == null || tokens.length == 0)
            return 0;
        
        Stack<Integer> stack = new Stack<Integer>();
        
        for(int i = 0; i < tokens.length; i++){
            if(!isOp(tokens[i])){
                stack.push(Integer.parseInt(tokens[i]));
            }
            else{
                int num2 = stack.pop();
                int num1 = stack.pop();
                
                if(tokens[i].equals("+"))
                    stack.push(num1 + num2);
                else if(tokens[i].equals("-"))
                    stack.push(num1 - num2);
                else if(tokens[i].equals("*"))
                    stack.push(num1 * num2);
                else
                    stack.push(num1 / num2);
            }
        }
        
        return stack.pop();
    }
    
    public boolean isOp(String str){
        return (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"));
    }
}

 

以上是关于lintcode-medium-Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章