Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
python
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
firstHalf=['{','[','(']
dict = {'}':'{',']':'[',')':'('}
stack=[]
for c in s:
if not stack or c in firstHalf:
stack.append(c)
elif dict[c]!=stack.pop() :
return False
if not stack:
return True
else:
return False