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

20. 有效的括号

题目链接:20. 有效的括号
思路:由于栈结构的特殊性,非常适合做对称匹配类的题目。这题字符串里的括号不匹配有几种情况

  • 第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false
  • 第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false
  • 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false

字符串遍历完之后,栈是空的,就说明全都匹配了。在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了,比左括号先入栈代码实现要简单的很多!
代码如下:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for item in s:
            if item == "(":
                stack.append(")")
            if item == "{":
                stack.append("}")
            if item == "[":
                stack.append("]")
            elif not stack or stack[-1] != item:
                return False
            else:
                stack.pop()
        return True if not stack else False

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

使用字典和栈来实现

代码如下:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {'(': ')',
                   '{': '}',
                   '[': ']'}
        for item in s:
            if item in mapping.keys():
                stack.append(mapping[item])
            elif not stack or stack[-1] != item:
                return False
            else:
                stack.pop()
        return True if not stack else False

学习时长
30分钟

1047. 删除字符串中的所有相邻重复项

题目链接:1047. 删除字符串中的所有相邻重复项

用栈解决

代码如下:

class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list()
        for item in s:
            if res and res[-1] == item:
                res.pop()
            else:
                res.append(item)
        return " ".join(res)
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

使用双指针模拟栈

代码如下:

class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list(s)
        slow,fast = 0,0
        while fast < len(res):
            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])

学习时长
30分钟

150. 逆波兰表达式求值

题目链接;150. 逆波兰表达式求值

使用字典

代码如下:

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 in self.op_map.keys():
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(self.op_map[token](op1, op2))
            else:
                stack.append(int(token))
        return stack.pop()

使用eval函数

eval函数介绍python字符串格式化f_string介绍
代码如下:

class Solution:
    op_map = ['+', '-', '*', '/']
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token in self.op_map:
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(int((eval(f'{op1}{token}{op2}'))))
            else:
                stack.append(token)
        return int(stack.pop())

学习时长
30分钟

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值