leetcode----150. Evaluate Reverse Polish Notation

链接:

https://leetcode.com/problems/evaluate-reverse-polish-notation/

大意:

给一个逆波兰表达式tokens,求出该表达式的值。规定:逆波兰表达式中运算符只有 '+' '-' '*' '/' 例子:

思路:

使用一个操作数栈,遍历tokens。

如果当前字符串可以对应一个整数,那将其转为整数并压入操作数栈中

如果当前字符串是一个操作符ope,则依次取两次栈顶元素(使用删除栈顶元素),即为num2,num1.将num1 ope num2的结果压入栈。

最后栈中将只剩一个元素,这个元素即为所求的结果

代码:

class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens.length == 0)
            return 0;
        ArrayList<Integer> stack = new ArrayList<>();
        for (String str : tokens) {
            char c = str.charAt(0);
            // ‘+’和‘-’既可以表示一个数的正负 也可以表示一个运算符
            if ((c == '+' && str.length() == 1) || (c == '-' && str.length() == 1) || c == '*' || c == '/') {
                if (c == '+') {
                    int num2 = stack.remove(stack.size() - 1), num1 = stack.remove(stack.size() - 1);
                    stack.add(num1 + num2);
                }
                if (c == '-') {
                    int num2 = stack.remove(stack.size() - 1), num1 = stack.remove(stack.size() - 1);
                    stack.add(num1 - num2);
                }
                if (c == '*') {
                    int num2 = stack.remove(stack.size() - 1), num1 = stack.remove(stack.size() - 1);
                    stack.add(num1 * num2);
                }
                if (c == '/') {
                    int num2 = stack.remove(stack.size() - 1), num1 = stack.remove(stack.size() - 1);
                    stack.add(num1 / num2);
                }
            } else {
                stack.add(Integer.valueOf(str));
            }
        }
        return stack.remove(0);
    }
}

结果:

结论:

有关栈问题且很基础的一个题。 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/89431500