这一题的思路就是创建一个栈用来存储括号,具体思路如下:
1.如果栈为空则直接入栈,遍历下一个括号
2.接下来依次比对括号是否为)、}、]中的一种,并与栈顶元素匹配,匹配则出栈
3.最后判断栈是否为空,为空则输出true,否则输出false
class Solution:
def isValid(self , s:str )->bool:
# write code here
stack = []
for i in s:
if not stack:
stack.append(i)
continue
if i == ')' and stack[-1]== '(':
stack.pop()
elif i == '}' and stack[-1]== '{':
stack.pop()
elif i == ']' and stack[-1]== '[':
stack.pop()
else:
stack.append(i)
return True if not stack else False