题意: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.
代码:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for i in xrange(len(s)):
if stack and ((stack[-1] =='(' and s[i]==')') or (stack[-1] =='[' and s[i]==']') or (stack[-1] =='{' and s[i]=='}')):
stack.pop()
else:
stack.append(s[i])
return len(stack)==0
参考代码:
def isValid(self, s):
stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0