【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值

来源:互联网 发布:诺基亚淘宝官方旗舰店 编辑:程序博客网 时间:2024/05/17 03:25

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

样例
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
说明
什么是逆波兰表达式?
http://en.wikipedia.org/wiki/Reverse_Polish_notation

public class Solution {    /**     * @param tokens The Reverse Polish Notation     * @return the value     */    public int evalRPN(String[] tokens) {        if(null == tokens || tokens.length == 0) return 0;        Set<String> cSet = new HashSet<String>();        cSet.add("+");        cSet.add("-");        cSet.add("*");        cSet.add("/");        Stack<Integer> stack = new Stack<Integer>();        for(int i = 0; i < tokens.length; i++) {            if(!cSet.contains(tokens[i])) {                stack.push(Integer.valueOf(tokens[i]));            }else {                int b = stack.pop();                int a = stack.pop();                int c = 0;                char[] arr = tokens[i].toCharArray();                switch (arr[0]){                    case '+':                        c = a + b;                        break;                    case '-':                        c = a - b;                        break;                    case '*':                        c = a * b;                        break;                    case '/':                        c = a / b;                }                stack.push(c);            }        }        return stack.peek();    }}
0 0
原创粉丝点击