class Solution:
def isValid(self, s: str) -> bool:
stack = []
left = {'(':0, '{':1, '[':2} #左括号字典
right = {')':0, '}':1, ']':2} #右括号字典
for ch in s:
if ch in left: #是左括号
stack.append(ch)
else: #是右括号
if len(stack) > 0 and left[stack[-1]] == right[ch]:
stack.pop()
else:
return False
return len(stack) == 0
2020.3.24
class Solution:
def isValid(self, s: str) -> bool:
l = '([{' #左括号集
r = ')]}' #右括号集,顺序与左括号一一对应
stack = []
for c in s:
if c in l:
stack.append(c)
else: #右括号
if len(stack) > 0: #栈非空,取出栈顶比较,序号相等则匹配
if l.index(stack[-1]) == r.index(c):
stack.pop()
else: #匹配不上
return False
else: #栈空,遇到单独右括号
return False
return len(stack) == 0
2024.3.30
class Solution:
def isValid(self, s: str) -> bool:
l = '([{' #左括号集
r = ')]}'
stack = []
for c in s:
if c in l:
stack.append(c)
else:
# 右括号只有匹配 和 不匹配 两种情况,匹配则弹栈,不匹配直接返回
if len(stack) > 0 and r.index(c) == l.index(stack[-1]):
stack.pop()
else:
return False
return len(stack) == 0