150. Evaluate Reverse Polish Notation

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

 

 

Subscribe to see which companies asked this question

Hide Tags
 Stack
 
 
public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens.length == 0)
            return 0;
            
        Deque<Integer> stack = new ArrayDeque<Integer>();
        
        for(String str: tokens)
        {
            if(str.equals("+"))
                stack.push(stack.pop()+stack.pop());
            else if(str.equals("-"))
            {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2-v1);
            }
            else if(str.equals("/"))
            {
                int v1 = stack.pop();
                int v2 = stack.pop();
                stack.push(v2/v1);
            }
            else if(str.equals("*"))
                stack.push(stack.pop()*stack.pop());    
            else
                stack.push(Integer.parseInt(str));
        }
        return stack.pop();
    }
}

 

 
posted @ 2016-04-27 13:01  新一代的天皇巨星  阅读(139)  评论(0)    收藏  举报