2014年4月29日 星期二

[LeetCode] 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.
Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Solution:O(n)

public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens == null || tokens.length == 0)
            return 0;
        Stack<String> stack = new Stack<>();
        for(String s:tokens){
            if(s.equals("+")){
                int s1 = Integer.parseInt(stack.pop());
                int s2 = Integer.parseInt(stack.pop());
                stack.push(""+(s1+s2));
            }
            else if(s.equals("-")){
                int s1 = Integer.parseInt(stack.pop());
                int s2 = Integer.parseInt(stack.pop());
                stack.push(""+(s2-s1));
            }
            else if(s.equals("*")){
                int s1 = Integer.parseInt(stack.pop());
                int s2 = Integer.parseInt(stack.pop());
                stack.push(""+(s1*s2));
                
            }else if(s.equals("/")){
                 int s1 = Integer.parseInt(stack.pop());
                int s2 = Integer.parseInt(stack.pop());
                stack.push(""+(s2/s1));
                
            }else{
                stack.push(s);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

沒有留言:

張貼留言