美文网首页
leetcode150.逆波兰表达式求值

leetcode150.逆波兰表达式求值

作者: 今天不想掉头发 | 来源:发表于2019-08-19 19:56 被阅读0次

使用一个辅助栈就可以了。。

public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String s : tokens) {
            if (s.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (s.equals("-")) {
                stack.push(-stack.pop() + stack.pop());
            } else if (s.equals("*")) {
                stack.push(stack.pop() * stack.pop());
            } else if (s.equals("/")) {
                int num = stack.pop();
                stack.push(stack.pop() / num);
            } else {
                stack.push(Integer.parseInt(s));
            }
        }
        return stack.pop();
    }

相关文章

网友评论

      本文标题:leetcode150.逆波兰表达式求值

      本文链接:https://www.haomeiwen.com/subject/ninesctx.html