思路:用一個字符串來模擬入棧和出棧,如果是左括號則入棧,如果是右括號則出棧,如果是一個有效的括號,那麼最終這個棧一定是空的
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
# if s.startswith(")") or s.startswith("]") or s.startswith("}"):
# return False
#用一個字符串來模擬入棧出棧
s1 = ""
for ss in s:
if ss == "(" or ss == "[" or ss == "{":
s1 += ss
#print s1
else:
if len(s1) < 1:
return False
if ss == ")":
if s1[-1] == "(":
s1 = s1[:-1]
continue
else:
return False
elif ss == "]":
if s1[-1] == "[":
s1 = s1[:-1]
continue
else:
return False
elif ss == "}":
if s1[-1] == "{":
s1 = s1[:-1]
continue
else:
return False
return s1 == ""