用栈解决后缀表达式问题(逆波兰表达法)150. Evaluate Reverse Polish Notation

很有意思的一道题,用switch写出来非常简洁。
今天才知道JAVA的Stack类非常老(JDK1.0就引入了)而且非常的慢,所以最好用ArrayDeque来代替,感谢StackOverFlow上各路大神解答我的问题。
问题链接

本题代码如下:

class Solution {
    public int evalRPN(String[] tokens) {
        ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
        for(String s: tokens){
                switch (s) {
                    case "+" : stack.push(stack.pop() + stack.pop()); break;
                    case "-" : int temp = stack.pop(); stack.push(stack.pop() - temp); break;
                    case "*" : stack.push(stack.pop() * stack.pop()); break;    
                    case "/" : int denominator = stack.pop(); stack.push(stack.pop() / denominator);  break;    
                    default : stack.push(Integer.parseInt(s));
                }      
        }
        return stack.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44015873/article/details/85631810