20. Valid Parentheses
Given a string
s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.Note: Remember to think what happens with remaining items on stack?
def isValid(s: str):
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for c in s:
if c in pairs.values():
stack.append(c)
else:
if not stack or (stack[-1] != pairs[c]):
return False
stack.pop()
return not stack
Comments
Post a Comment