LeetCode150——逆波兰表达式求值

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/description/

题目描述:

LeetCode150——逆波兰表达式求值_第1张图片

知识点:逆波兰表达式求值、栈

思路:逆波兰表达式求值

逆波兰表达式的计算规则:

从左往右遍历表达式的每个数字和符号,遇到是数字就进栈, 遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。

时间复杂度和空间复杂度均是O(n),其中n为输入的字符串数组的大小。

JAVA代码:

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

LeetCode解题报告:

LeetCode150——逆波兰表达式求值_第2张图片

 

你可能感兴趣的:(LeetCode题解,LeetCode,逆波兰表达式,栈)