有效的括号 python

2021-08-06 10:56

阅读:577

标签:lis   and   字符   不为   rgb   方法   solution   code   list   # 给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串 s ,判断字符串是否有效。 # # 有效字符串需满足: # # # 左括号必须用相同类型的右括号闭合。 # 左括号必须以正确的顺序闭合。 # # # # # 示例 1: # # # 输入:s = "()"# 输出:true 方法:根据栈性质 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def isValid(self, s: str) -> bool: if len(s) % 2 == 1: return False stack = list() # 初始堆 pairs = {"}": "{", ")": "(", "]": "["} # 建立哈希表 for ch in s: # 当前字符是左字符,要出栈 if ch in pairs: # 栈不为空,但栈的最后一个元素不是左字符,不合法 if not stack or stack[-1] != pairs[ch]: return False stack.pop() # 右字符要入栈 else: stack.append(ch) # 最终栈为空就是合法了 return not stack # leetcode submit region end(Prohibit modification and deletion)  有效的括号 python标签:lis   and   字符   不为   rgb   方法   solution   code   list   原文地址:https://www.cnblogs.com/demo-deng/p/14949679.html


评论


亲,登录后才可以留言!