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])
相关推荐
努力写A题的小菜鸡1 分钟前
01-PyTorch加载数据初认识(dataset运用)
人工智能·pytorch·python
abcy0712134 分钟前
python fastapi celery hdfs 异步上传
python·hdfs·fastapi
TMT星球5 分钟前
魔法原子上交会首秀VLA K02大模型,完成具身智能从“执行”到“理解”的能力跃迁
人工智能·算法·机器学习
Dxy12393102166 分钟前
Python多线程如何操作全局变量:从踩坑到最佳实践
python
2301_764441337 分钟前
番茄钟+AI:高效专注的秘密武器
人工智能·算法·数学建模·动态规划·交互
影寂ldy10 分钟前
C# 泛型委托
java·算法·c#
SilentSamsara11 分钟前
RAG 系统入门:LangChain/LlamaIndex + Chroma 向量数据库的检索增强实战
数据库·人工智能·python·青少年编程·langchain
码云骑士23 分钟前
06-Python装饰器从入门到源码(上)-闭包与自由变量
开发语言·python
星马梦缘24 分钟前
算法设计与分析 作业三 纯答案
算法