思路:用一个字符串来模拟入栈和出栈,如果是左括号则入栈,如果是右括号则出栈,如果是一个有效的括号,那么最终这个栈一定是空的
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 == ""