# using a stack data structure
def isValid(s):
if len(s) == 0: return True
if len(s)%2 !=0: return False
l = []
for elem in s:
if len(l) == 0: l.append(elem)
else:
if (l[-1] + elem) in ['()', '[]', '{}']:
l.pop() # current element finds a pair in history stack
else:
l.append(elem) # current element does not find a pair in history stack
# the algorithm goes that if an the history is eventually empty, that means all pairs are eliminated
if len(l) == 0:
return True
else:
return False
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.