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("/"));
    }
}

 

posted @ 2016-03-20 13:51  哥布林工程师  阅读(121)  评论(0编辑  收藏  举报