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])
相关推荐
10岁的博客8 分钟前
PyTorch快速搭建CV模型实战
人工智能·pytorch·python
寒秋丶33 分钟前
AutoGen多智能体协作、人机交互与终止条件
人工智能·python·microsoft·ai·人机交互·ai编程·ai写作
Turnsole_y42 分钟前
pytest与Selenium结合使用指南
开发语言·python
AI量化投资实验室2 小时前
年化398%,回撤11%,夏普比5,免费订阅,5积分可查看参数|多智能体的架构设计|akshare的期货MCP代码
人工智能·python
Jasmine_llq2 小时前
《P2656 采蘑菇》
算法·强连通分量·广度优先搜索(bfs)·tarjan 算法·图的缩点操作·有向无环图(dag)·最长路径
芥子沫2 小时前
《人工智能基础》[算法篇3]:决策树
人工智能·算法·决策树
mit6.8242 小时前
dfs|位运算
算法
苏纪云2 小时前
算法<C++>——双指针 | 滑动窗口
数据结构·c++·算法·双指针·滑动窗口
保持低旋律节奏2 小时前
算法——二叉树、dfs、bfs、适配器、队列练习
算法·深度优先·宽度优先