class Solution:
def isValid(self, s):
p=[
(s.count("(")+s.count(")"))%2!=0,
(s.count("[")+s.count("]"))%2!=0,
(s.count("{")+s.count("}"))%2!=0,
]
if p[0] or p[1] or p[2]:
return False
replace=[
["()",""],
["[]",""],
["{}",""],
]
while True:
for rep in replace:
s=s.replace(rep[0],rep[1])
if not (("()" in s) or ("[]" in s) or ("{}" in s)):
break
if len(s):
return False
else:
return True
解题思路:
首先判断每种括号的字符数量是否为偶数(也就是看是否有完整的括号)
如果为否,则返回False
如果为是,则执行下面的代码
把中间没有其它字符的括号依次删除
删完后如果s中还有字符就返回False
如果没有字符了,就返回True
关注我,在Leetcode专栏中查看更多题目的解题思路吧!
本文介绍了如何使用Python实现一个有效的括号匹配算法,检查输入字符串中的括号是否正确闭合。首先检查每种括号的数量是否为偶数,然后逐步删除完整括号对,直到字符串为空或仍有未匹配的括号。该算法适用于LeetCode等编程挑战,涉及字符串处理和逻辑判断。
198

被折叠的 条评论
为什么被折叠?



