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.
Subscribe to see which companies asked this question
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
s_list = list(s)
sstack = []
for item in s_list:
if item in ['{','(','[']:
sstack.append(item)
else:
try:
if item == '}':
temp = sstack.pop()
if temp != '{':
return False
elif item == ')':
temp = sstack.pop()
if temp != '(':
return False
elif item == ']':
temp = sstack.pop()
if temp != '[':
return False
except Exception,e:
return False
if len(sstack) == 0:
return True
else:
return False