python leetcode 20 有效的括号 【简单题】

1. 读懂题目

2. 分析,推导解法,产生思路。

特殊情况处理即个数不匹配;

(1)list模拟栈:.append  .pop;字典的键值利用;

(2)repalce()子串替换
        # 反复替换: "([])"  停止条件:没有能删除的配对字符即此轮字符长度与上轮一致;

3 代码实现:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 == 1: # 特殊情况,个数不匹配
            return False

        # 1 list模拟栈:.append  .pop
        stack = list()
        pairs =  { ")": "(", "]": "[", "}": "{",}
        ch = 0
        while ch < len(s) : # 遍历字符
            if s[ch] in pairs:  # 若为字典的键即右括号则进入匹配
                if not stack or stack[-1] != pairs[s[ch]]: # 栈为空或不能匹配则False
                    return False
                stack.pop() # 匹配则出栈
            else:        # 若为字典的键即左括号则入栈
                    stack.append(s[ch]) # 入栈
            ch = ch + 1
        return not stack
        # 2 python字符串函数
        # repalce()子串替换
        # 反复替换: "([])"  停止条件:没有能删除的配对字符即此轮字符长度与上轮一致;

        # 2.1 引入额外的s_sub子串
        s_sub = s.replace('()', '').replace('{}','').replace('[]','')
        while len(s_sub) < len(s):
            s = s_sub   # 替换字符
            s_sub = s.replace('()', '').replace('{}','').replace('[]','')
        return not s_sub

        # 2.2 引入额外的len_before字段
        while True:
            len_before = len(s) # 记录替换之前的字符串长度
            s = s.replace('()', '').replace('{}','').replace('[]','')   # 字串替换
            if len_before == len(s): #字串长度前后比较
                break
        return not s

        # 2.1与2.2的内存与执行时间差距不大;1(4ms)比2(51ms)执行速度快很多,内存差距不大

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值