代码随想录算法训练营day9(栈与队列)

华子目录

  • 逆波兰表达式求值
    • 思路

逆波兰表达式求值

  • https://leetcode.cn/problems/evaluate-reverse-polish-notation/

代码随想录算法训练营day9(栈与队列)_第1张图片

思路

  • 初始化一个
  • 遍历整个tokens,遇到数字时将其压入到中,遇到运算符时,从中取两个数字进行运算,将运算完的结果压入到中,继续向后遍历
  • 遍历完后,留在中的元素就是最后的结果return即可
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []   # 存放的是整数
        arr = ['+','-','*','/']
        for i in tokens:
            if i not in arr:   # 说明是数字
                stack.append(int(i))
            else:
                num1 = stack.pop()
                num2 = stack.pop()
                if i == '+':
                    stack.append(num2 + num1)
                elif i == '-':
                    stack.append(num2 - num1)
                elif i == '*':
                    stack.append(num2 * num1)
                else:
                    stack.append(int(num2 / num1))
        return stack.pop()

你可能感兴趣的:(算法,开发语言,python)