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
python
class Solution(object):
def inValid(self,s):
num=[]
for i in range(len(s)):
if s[i]=="(" or s[i]=="{" or s[i]=="[":
num.append(s[i])
else:
if len(num):
temp=num[-1]
if s[i]==")":
if temp=="(":
num.pop()
else:
return False
if s[i]=="}":
if temp=="{":
num.pop()
else:
return False
if s[i]=="]":
if temp=="[":
num.pop()
else:
return False
else:
return False
if not len(num):
return True
else:
return False
C=Solution()
s="("
print C.inValid(s)