首页 > 其他 > 详细

Evaluate Reverse Polish Notation

时间:2015-06-15 06:51:32      阅读:238      评论:0      收藏:0      [点我收藏+]

很简单的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;
        }
    }
}

 

Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/jiajiaxingxing/p/4576237.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!