LeetCode——逆波兰表达式求值

Q:计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
例如:

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

A:使用栈,碰到符号就跳出来两个值计算再压入结果

import java.util.Stack;
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack();
        for (int i = 0; i < tokens.length; i++) {
            try {
                int num = Integer.parseInt(tokens[i]);
                stack.push(num);
            } catch (Exception e) {
                int a = stack.pop();
                int b = stack.pop();
                if (tokens[i].equals("+"))
                    stack.push(a + b);
                else if (tokens[i].equals("-"))
                    stack.push(b - a);
                else if (tokens[i].equals("*"))
                    stack.push(a * b);
                else if (tokens[i].equals("/"))
                    stack.push(b / a);
            }
        }
        return stack.pop();
    }
posted @ 2020-03-06 15:26  Shaw_喆宇  阅读(143)  评论(0编辑  收藏  举报