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, 每次遇到operator就从stack里取出2个数,后取出的数 运算符 先取出的数,然后再放回stack里。遇到数字直接放入stack里。switch不支持string,换成index。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> stack=new Stack<String>();
        String operators="+-*/";
        for(String t:tokens){
            if(!operators.contains(t)){
                stack.push(t);
            }else{
                int index=operators.indexOf(t);
                int b=Integer.valueOf(stack.pop());
                int a=Integer.valueOf(stack.pop());
                    
                switch(index){
                case 0:         
                    stack.push(String.valueOf(a+b));
                    break;
                case 1:
                    stack.push(String.valueOf(a-b));
                    break;
                case 2:
                    stack.push(String.valueOf(a*b));
                    break;
                case 3:
                    stack.push(String.valueOf(a/b));
                    break;          
                }
            }
        }
        
        return Integer.valueOf(stack.pop());
    }
}

 

posted on 2014-06-30 08:13  青椰子  阅读(122)  评论(0)    收藏  举报

导航