「Leetcode刷题」「20」有效的括号-开运vip手机官网登录

「Leetcode刷题」「20」有效的括号

2026-12-06 22:51:41投稿人:开运提款快速得(株洲)有限公司围观4931次63 评论

「Leetcode刷题」「20」有效的括号

"""找入栈条件,出栈条件	,栈顶与下一个元素的关系
,栈长度来判断"""# leetcode submit region begin(Prohibit modification and deletion)class Solution:    def isValid(self, s: str) ->bool:        stack = []        for char in s:            if self.is_left_kuohao(char):                stack.append(char)                continue            if self.is_right_kuohao(char):                if len(stack) == 0:                    return False                left_part = stack.pop()                if self.match_kuohao(left_part,char):                    continue                else:                    return False        return len(stack) == 0    def is_left_kuohao(self, char):        return char in "([{ "    def is_right_kuohao(self, char):        return char in ")]}"    def match_kuohao(self, left_part, right_part):        if left_part == "(" and right_part == ")":            return True        if left_part == "[" and right_part == "]":            return True        if left_part == "{ " and right_part == "}":            return True        return False# leetcode submit region end(Prohibit modification and deletion)


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

如果是第一次阅读文章,可以看看下面的话 。

以上内容由平时积累而成 ,尽量保证代码与注释合在一起 ,并未做过多篇幅的解释 。不一定是最优解,但一定是自己能看得懂的 。有疑问的地方还请留言评论 。如果题干是原题,就没有写在文章中。后续内容会慢慢发出

欢迎大家评论,收藏和转发。

感谢大家的点赞和关注。

先赞后看,年薪百万

红帽帽 ,白签签,一起排队做酸酸 。愿疫情早日过去。

展开阅读全文

投稿时间 :2022-05-22  最后更新 :2022-09-04