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])
相关推荐
java1234_小锋9 分钟前
一周学会Flask3 Python Web开发-flask3上下文全局变量session,g和current_app
python·flask·flask3
larance16 分钟前
Flask 发送邮件
后端·python·flask
m0_7482402518 分钟前
python轻量级框架-flask
开发语言·python·flask
pk_xz12345631 分钟前
基于Python和Neo4j开发的医疗辅助诊断系统的详细实现步骤和代码示例
python·oracle·neo4j
web_155342746561 小时前
性能巅峰对决:Rust vs C++ —— 速度、安全与权衡的艺术
c++·算法·rust
硬件人某某某1 小时前
基于Django的手办交易平台~源码
后端·python·django
升讯威在线客服系统1 小时前
如何通过 Docker 在没有域名的情况下快速上线客服系统
java·运维·前端·python·docker·容器·.net
久绊A3 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J7 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶7 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn