题目:
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.
方法一:性能59ms
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) < 2:
return False
str1 = []
for i in range(len(s)):
str1.append(s[i])
left = ['(','[','{']
right = [')',']','}']
str2 = []
while len(str1) > 0:
if str1[0] in left:
str2.append(str1.pop(0))
elif len(str2) > 0:
#a = list.index(str2[-1],left)
for i in range(3):
if str2[-1] == left[i]:
a = i
#b = list.index(str1[0],right)
for i in range(3):
if str1[0] == right[i]:
b = i
if a != b:
return False
else:
str2.pop()
str1.pop(0)
else:
return False
if len(str2) == 0:
return True
else:
return False
方法二:性能35ms
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dt = {')': '(', ']': '[', '}': '{'}
stack = []
for char in s:
if char not in dt:
stack.append(char)
else:
if len(stack) == 0 or stack.pop() != dt[char]:
return False
return True if len(stack) == 0 else False