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

[leedcode 150] Evaluate Reverse Polish Notation

时间:2015-08-01 21:45:38      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

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
public class Solution {
    //对于逆波兰式,一般都是用栈来处理,依次处理字符串,

    //如果是数值,则push到栈里面

    //如果是操作符,则从栈中pop出来两个元素,计算出值以后,再push到栈里面,

    //则最后栈里面剩下的元素即为所求。
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<Integer>();
        for(int i=0;i<tokens.length;i++){
            if(!isDigit(tokens[i])){
                stack.push(Integer.parseInt(tokens[i]));
                continue;
            }
            int num1=stack.pop();
            int num2=stack.pop();
            if(tokens[i].equals("-")){
                stack.push(num2-num1);
            }
            if(tokens[i].equals("+")){
                stack.push(num1+num2);
            }
            if(tokens[i].equals("*")){
                stack.push(num1*num2);
            }
            if(tokens[i].equals("/")){
                stack.push(num2/num1);
            }
        }
        return stack.pop();
    }
    public boolean isDigit(String s){
        if(s.equals("-")||s.equals("+")||s.equals("*")||s.equals("/")) return true;
        return false;
    }
}

 

[leedcode 150] Evaluate Reverse Polish Notation

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4694645.html

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