20. Valid Parentheses
# Easy
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# edge case
if len(s)%2 != 0: # odd, then must be false
return False
# regular case
dic = {'(': ')', '[': ']', '{': '}'}
left = set(['(', '[', '{'])
stack = []
for item in s:
if item in left:
stack.append(item)
elif stack and item == dic[stack[-1]]:
stack.pop()
else:
return False
return stack == []
Time complexity = , space comlexity =
Last updated
Was this helpful?