Problem:
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.
Idea:
Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return False
.
Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return True
, else return False
.
Solution:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = list()
for item in s:
if item == '(' or item == '{' or item == '[' :
l.append(item)
elif item == ')':
if len(l) == 0:
return False
elif l[len(l)-1] == '(':
l.pop()
else:
return False
elif item == '}':
if len(l) == 0:
return False
elif l[len(l)-1] == '{':
l.pop()
else:
return False
elif item == ']':
if len(l) == 0:
return False
elif l[len(l)-1] == '[':
l.pop()
else:
return False
if len(l) == 0:
return True
else:
return False