lintcode--逆波兰表达式求值

来源:互联网 发布:网络整天不稳定 编辑:程序博客网 时间:2024/05/17 08:55

求逆波兰表达式的值。

在逆波兰表达法中,其有效的运算符号包括 +-*,/ 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

/*思路:碰到不是+*-/就转换为整数压栈,碰到了就弹出两个数进行运算,得到的结果再压栈。最后压出最后的值*/public class Solution {    public int evalRPN(String[] tokens) {        Stack<Integer> s = new Stack<Integer>();        String operators = "+-*/";        for(String token : tokens){            if(!operators.contains(token)){                s.push(Integer.valueOf(token));                continue;//不能用break            }            int a = s.pop();            int b = s.pop();            if(token.equals("+")) {                s.push(b + a);            } else if(token.equals("-")) {                s.push(b - a);            } else if(token.equals("*")) {                s.push(b * a);            } else {                s.push(b / a);            }        }        return s.pop();    }}

原创粉丝点击