leetCode题目
一.
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效
有效字符串需满足
1. 左括号必须用相同类型的右括号闭合
2. 左括号必须以正确的顺序闭合
注意空字符串可被认为是有效字符串
def valid(s):
ss = []
a = True
index = 0
while index < len(s) and a:
symbol = s[index]
if symbol in '({[':
ss.append(symbol)
else:
if len(ss) == 0:
a = False
else:
bol = ss.pop()
if not '({['.index(bol) == ')}]'.index(symbol):
a = False
index += 1
if a and len(ss) == 0:
return True
else:
return False
从左到右处理符号时,最近开始的符号必须与下一个关闭的符号相匹配,程序将开始符号从左到右依次读取,并将其存储到一个空列表当中,直到遇到都一个关闭符号,然后将最后一个开始符号pop出去并与这个遇到的关闭符号进行匹配,如果匹配成功则继续进行下一轮匹配

喜欢开源,乐于分享,请多指教

浙公网安备 33010602011771号