给定一个仅包含字符 '(', ')', '{', '}', '[' 和 ']' 的字符串 s,判断输入字符串是否有效。
输入字符串在以下情况下有效:
左括号必须用相同类型的括号封闭。 左括号必须按正确的顺序关闭。 每个右括号都有一个对应的相同类型的左括号。
示例1:
输入:s =“()” 输出:真 示例2:
输入:s = "()[]{}" 输出:真 例3:
输入:s =“(]” 输出:假
限制:
1 <= s.length <= 104 s consists of parentheses only '()[]{}'.
类解决方案: @静态方法 def isBalanced(s): dict_mapping = {'}': '{', ')': '(', ']': '['} open_stack = []
for char in s:
if char in dict_mapping.values():
open_stack.append(char)
elif char in dict_mapping.keys():
if not open_stack or open_stack.pop() != dict_mapping[char]:
return False
else:
# Handle characters other than parentheses, braces, and brackets
return False
return len(open_stack) == 0
您应该使用
open_stack[-1]
而不是 open_stack.pop()
如果检查使用了 open_stack.pop(),则左括号将在没有正确检查的情况下被删除