码迷,mamicode.com
首页 > 其他好文 > 详细

Evaluate Reverse Polish Notation

时间:2014-06-30 23:46:14      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   for   io   

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());
    }
}

 

Evaluate Reverse Polish Notation,布布扣,bubuko.com

Evaluate Reverse Polish Notation

标签:style   blog   http   color   for   io   

原文地址:http://www.cnblogs.com/qingyezi/p/3815952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!