代码随想录算法训练营第十一天|20. 有效的括号,1047. 删除字符串中的所有相邻重复项,150. 逆波兰表达式求值

今天是代码随想录算法训练营第十一天;

写了3道力扣:20. 有效的括号,1047. 删除字符串中的所有相邻重复项,150. 逆波兰表达式求值

  1. 有效的括号:
python 复制代码
# 方法一,仅使用栈,更省空间
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        
        for item in s:
            if item == '(':
                stack.append(')')
            elif item == '[':
                stack.append(']')
            elif item == '{':
                stack.append('}')
            elif not stack or stack[-1] != item:
                return False
            else:
                stack.pop()
        
        return True if not stack else False
  1. 删除字符串中的所有相邻重复项
python 复制代码
# # 方法一,使用栈
# class Solution:
#     def removeDuplicates(self, s: str) -> str:
#         res = list()
#         for item in s:
#             if res and res[-1] == item: # 如果栈非空 且 栈顶元素等于传入进来的item
#                 res.pop() # 那么就进行消除操作
#             else:
#                 res.append(item)
#         return "".join(res)  # 字符串拼接


# 此题还可以用双指针的方法
# 方法二,使用双指针模拟栈,如果不让用栈可以作为备选方法。
class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list(s)
        slow = fast = 0
        length = len(res)

        while fast < length:
            # 如果一样直接换,不一样会把后面的填在slow的位置
            res[slow] = res[fast]
            
            # 如果发现和前一个一样,就退一格指针
            if slow > 0 and res[slow] == res[slow - 1]:
                slow -= 1
            else:
                slow += 1
            fast += 1
            
        return ''.join(res[0: slow])
  1. 逆波兰表达式求值
python 复制代码
from operator import add, sub, mul

class Solution:
    op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
    
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token not in {'+', '-', '*', '/'}:
                stack.append(int(token))
            else:
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(self.op_map[token](op1, op2))  # 第一个出来的在运算符后面
        return stack.pop()
相关推荐
默默前行的虫虫1 分钟前
MQTT.fx实际操作
python
艾莉丝努力练剑10 分钟前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法
YMWM_10 分钟前
python3继承使用
开发语言·python
JMchen12311 分钟前
AI编程与软件工程的学科融合:构建新一代智能驱动开发方法学
驱动开发·python·软件工程·ai编程
Once_day26 分钟前
C++之《程序员自我修养》读书总结(1)
c语言·开发语言·c++·程序员自我修养
偷吃的耗子41 分钟前
【CNN算法理解】:CNN平移不变性详解:数学原理与实例
人工智能·算法·cnn
喜欢喝果茶.44 分钟前
QOverload<参数列表>::of(&函数名)信号槽
开发语言·qt
亓才孓1 小时前
[Class类的应用]反射的理解
开发语言·python
努力学编程呀(๑•ี_เ•ี๑)1 小时前
【在 IntelliJ IDEA 中切换项目 JDK 版本】
java·开发语言·intellij-idea