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])
相关推荐
小O的算法实验室13 分钟前
2026年SEVC,面向主动成像卫星任务规划问题的群体智能与动态规划混合框架,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
网安INF23 分钟前
数据结构第一章复习:基本概念与算法复杂度分析
数据结构·算法
YuanDaima204830 分钟前
基于 LangChain 1.0 的检索增强生成(RAG)实战
人工智能·笔记·python·langchain·个人开发·langgraph
幻风_huanfeng1 小时前
人工智能之数学基础:什么是凸优化问题?
人工智能·算法·机器学习·凸优化
三雷科技1 小时前
使用 `dlopen` 动态加载 `.so` 文件
开发语言·c++·算法
RopenYuan1 小时前
FastAPI -API Router的应用
前端·网络·python
听风吹等浪起1 小时前
用Python和Pygame从零实现坦克大战
开发语言·python·pygame
Yzzz-F1 小时前
Problem - 2146D1 - Codeforces &&Problem - D2 - Codeforces
算法
Kk.08021 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
环黄金线HHJX.1 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互