25期代码随想录算法训练营第十天 | 栈与队列 part 2

目录

  • [20. 有效的括号](#20. 有效的括号)
  • [1047. 删除字符串中的所有相邻重复项](#1047. 删除字符串中的所有相邻重复项)
  • [150. 逆波兰表达式求值](#150. 逆波兰表达式求值)

20. 有效的括号

链接

python 复制代码
class Solution:
    def isValid(self, s: str) -> bool:
        closeToOpen = {")": "(", "]":"[", "}":"{"}
        stack = []

        for string in s:
            if string not in closeToOpen:
                stack.append(string)
            else:
                if not stack or stack.pop() != closeToOpen[string]:
                    return False
        
        return len(stack) == 0

1047. 删除字符串中的所有相邻重复项

链接

python 复制代码
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []

        for string in s:
            if not stack:
                stack.append(string)
            else:
                if string == stack[-1]:
                    stack.pop()
                else:
                    stack.append(string)
        return ''.join(stack)

150. 逆波兰表达式求值

链接

python 复制代码
from operator import add, mul, sub
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        op_map = {"+": add, "-": sub, "*": mul, "/": lambda x,y: int(x/y)}

        for token in tokens:
            if token not in op_map:
                stack.append(token)
            else:
                y = int(stack.pop())
                x = int(stack.pop())
                res = op_map[token](x, y)
                stack.append(res)
        
        return int(stack[-1])
相关推荐
黑十28 分钟前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python
D e re k ZH31 分钟前
P5025 [SNOI2017] 炸弹
c++·算法
A boy CDEF girl40 分钟前
算法题专栏:优选算法
数据结构·算法·leetcode
没落之王1 小时前
三易五行看宋朝的三界确立
大数据·人工智能·算法
threelab1 小时前
开源图片去水印代码
python
坤坤子吖1 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
taller_20002 小时前
【012】数据类型入门: Excel 数据到 Python 值的转换
python·excel·pie·py
淡漠的蓝精灵2 小时前
web.py:一个简单到极致的 Python Web 框架
开发语言·前端·python·其他
Js.Tx3 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
起个名字费劲死了3 小时前
Halcon学习一:骰子识别
前端·python·学习