思路,用两个堆栈数据结构,一边出一边进,如果两两不能抵消,说明无效。
步骤:
1、创建两个堆栈,mystack和stack,mystack里面放着所有的字符串,stack等待放从mystack退出的元素。
2、从mystack中取出元素如果是左边的,就放入stack,如果是右边的,从stack中取出一个元素看看是否能匹配,匹配就继续,不匹配就失败。
3、如果全都匹配就就返回true
4、如果还有剩下的,就失败。
class Solution:
def isValid(self, s: str) -> bool:
mystack = []
stack = []
for i in range(len(s)-1,-1,-1):
mystack.append(s[i])
while(mystack != []):
x = mystack.pop()
if(x == '(' or x == '[' or x == '{'):
stack.append(x)
else:
if stack == []:
return False
else:
y = stack.pop()
if(x == ')' and y =='('):
continue
elif(x == ']' and y =='['):
continue
elif (x == '}' and y == '{'):
continue
else:
return False
if stack ==[]:
return True
else:
return False
strs = ']'
a = Solution().isValid(strs)
print(a)