class Solution(object):
def isValid(self, s):
arr=[]
for i in s:
if i=='(' or i=='[' or i=='{':
arr.append(i)
elif i==')':
if len(arr)==0:
return False
f=arr.pop()
if f!='(':
return False
elif i==']':
if len(arr)==0:
return False
f=arr.pop()
if f!='[':
return False
elif i=='}':
if len(arr)==0:
return False
f=arr.pop()
if f!='{':
return False
else:
continue
if len(arr)!=0:
return False
return True
题解:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for item in s:
if item == '(':
stack.append(')')
elif item == '[':
stack.append(']')
elif item == '{':
stack.append('}')
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False