Evaluate Reverse Polish Notation

很简单的stack,注意operation order

public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens ==null|| tokens.length==0) return 0;
        Stack<String> st = new Stack<String>();
        String opr = "+-*/";
        for(int i=0;i<tokens.length;i++){
            if(!opr.contains(tokens[i])){
                st.push(tokens[i]);
            }else{
                cal(st,tokens[i]);
            }
        }
        return Integer.valueOf(st.pop());
    }
    private void cal(Stack<String> st, String op){
        int x = Integer.valueOf(st.pop());
        int y = Integer.valueOf(st.pop());
        switch(op){
            case "+": st.push(String.valueOf(x+y));
                      break;
            case "-": st.push(String.valueOf(y-x));
                      break;
            case "*": st.push(String.valueOf(x*y));
                      break;  
            case "/": st.push(String.valueOf(y/x));
                      break;
        }
    }
}

 

posted @ 2015-06-15 04:39  世界到处都是小星星  阅读(133)  评论(0编辑  收藏  举报