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])
相关推荐
FL16238631299 分钟前
基于yolov5的混凝土缺陷检测系统python源码+onnx模型+评估指标曲线+精美GUI界面
人工智能·python·yolo
立黄昏粥可温21 分钟前
Python 从入门到实战22(类的定义、使用)
开发语言·python
菜鸟求带飞_1 小时前
算法打卡:第十一章 图论part01
java·数据结构·算法
浅念同学1 小时前
算法.图论-建图/拓扑排序及其拓展
算法·图论
今天也要加油丫1 小时前
`re.compile(r“(<.*?>)“)` 如何有效地从给定字符串中提取出所有符合 `<...>` 格式的引用
python
是小Y啦1 小时前
leetcode 106.从中序与后续遍历序列构造二叉树
数据结构·算法·leetcode
程序猿练习生1 小时前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
liuyang-neu1 小时前
力扣 42.接雨水
java·算法·leetcode
y_dd1 小时前
【machine learning-12-多元线性回归】
算法·机器学习·线性回归