Friday, July 25, 2014

[LeetCode] 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

解题思路: 用一个stack即可
 public int evalRPN(String[] tokens) {
       Stack tmp = new Stack ();
       
       for(int i = 0; i < tokens.length; i++){
           if(tokens[i].matches("[+-]?\\d+")){
               tmp.add(Integer.valueOf(tokens[i]));
           }else{
            if(tmp.isEmpty()) return 0;
            
            int b = tmp.pop();
            int a = tmp.pop();
            
            switch(tokens[i]){
               case "+": a += b;
                         break;
               case "-": a -= b;
                         break;
               case "*": a *= b;
                         break;
               case "/": a /= b;
                         break;
               default: break;
            }
            
            tmp.add(a);
           }
       }
        
        return tmp.peek();
    }

No comments:

Post a Comment