有效的括号
1,将字符串变为列表
2,往后遍历,若碰到右括号,与前面的左括号抵消(以代数和形式表现)
3,若往前寻找左括号未找到,或找到右括号,则其和不为零,返回False
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# 设置字符字典
kuohao_dic = {"(": 1, "{": 2, "[": 3, ")": -1, "}": -2, "]": -3}
# 把字符串列表化
sl = list(s)
i = 0
c1 = 0
while i < len(sl):
c1 += 1
if kuohao_dic[sl[i]] < 0: # 遍历寻找第一个右括号
c1 -= 2
j = i
while True:
j -= 1
if j < 0:
return False
if kuohao_dic[sl[j]] == -kuohao_dic[sl[i]]:
sl.pop(i)
sl.pop(j)
i -= 2
break
if kuohao_dic[sl[j]] != -kuohao_dic[sl[i]]:
return False
i += 1
if c1 == 0:
return True
else:
return False