(Leetcode) 有效的括号 - Python实现

题目:

有效的括号: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。
    注意空字符串可被认为是有效字符串。

示例:

  输入: "()", 输出: true

  输入: "()[]{}", 输出: true

  输入: "(]", 输出: false

  输入: "([)]", 输出: false

  输入: "{[]}", 输出: true

--------------------------------------------------------------------------

解法1:对字符串进行循环替换,将所有成对的括号替换成空字符。就是效率偏低。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return True

        # 如果长度为奇数,返回False
        if len(s) % 2 == 1:
            return False

        for i in range(len(s)):
            s = s.replace("()", "").replace("[]", "").replace("{}", "")

        if len(s) > 0:
            return False
        else:
            return True

        return True

解法2:巧用字典和栈

解法逻辑:

先用字典 “反向存储” 括号字符对,eg. {")":"("}。

如果在stack中,存在"("(此时stack中有2个元素 [None,"("],长度为2),同时s的下一个字符是")"时,那么就从stack中剔除"(",stack只剩下[None],长度为1。

但如果在stack中,存在")",此时stack中有2个元素 [None,")"],长度为2),同时s的下一个字符是")"时,那么就在stack中添加一个"(",此时stack为[None, ")", "("], 长度为3。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """

        if len(s) == 0:
            return True

        # 如果长度为奇数,返回False
        if len(s) % 2 == 1:
            return False

        # 用字典 “反向存储” 括号字符
        dic = {")": "(", "]": "[", "}": "{"}
        
        stack = [None]

        for S in s:
            if S in stack and dic[S] == stack[-1]:
                stack.pop()
            else:
                stack.append(S)
        return len(stack) == 1

参考

https://blog.csdn.net/qiubingcsdn/article/details/81939360

https://blog.csdn.net/qq_34364995/article/details/80274117

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值