leetcode-20. 有效的括号

https://leetcode.cn/problems/valid-parentheses/
20. 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"
输出:true
示例 2:

输入:s = "()[]{}"
输出:true
示例 3:

输入:s = "(]"
输出:false

这个题要使用栈,

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        s_dict = {'(': ')', '[': ']', '{': '}'}

        for i in s:
            if i in ['(', '[', '{']:
                stack.append(i)
            else:
                if not stack:
                    return False
                a = stack.pop()
                if s_dict[a] != i:
                    return False
        if not stack:
            return True
        else:
            return False


if __name__ == '__main__':
    s = "{()[]{}()}"
    ss = Solution()
    print(ss.isValid(s))


posted @   技术改变命运Andy  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示