目录
栈
创建一个空栈,遍历给定的字符串。如果字符与栈顶括号不匹配,则将字符加入栈;如果匹配,则弹出栈顶元素。最后看栈是否为空。
注意,只有输入是‘右’括号时,才有可能弹出。否则可直接将字符加入栈。
class Solution:
def isValid(self, s: str) -> bool:
z = []
n = len(s)
d={}
d[')'] = '('
d[']'] = '['
d['}'] = '{'
for i in range(n):
if z == [] or s[i] not in d or z[-1] != d[s[i]]: #z == [] 可以写成 not z
z.append(s[i]) #不能写成 z is not None
else:
z.pop()
return False if z else True
if 的短路性
如上
if z == [] or s[i] not in d or z[-1] != d[s[i]]:
if z == [] or z[-1] != d[s[i]] or s[i] not in d:
#如果将 s[i] not in d 判断放在后面, 根据if判断语句的顺序,执行z[-1] != d[s[i]] 时,
#d[s[i]] 可能不存在,因为我们的字典里没有左括号,所以会报错。
#而第一种写法,根据 if 的短路性,s[i] not in d 时,后面将不会执行。