20. Valid Parentheses

# using a stack data structure def isValid(s): if len(s) == 0: return True if len(s)%2 !=0: return False l = [] l.append(s[0]) for elem in s[1:]: if elem == l[-1]: 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.