Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
解题要点:
1.栈的功能和配对,栈可以用列表去实现,一一配对的功能用两个字符串的下表去对应(当然也可以有其他方法,比如写一个判断的函数之类的);
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
lt = []
left = "{[("
right = "}])"
for i in s:
if i in left:
lt.append(i)
else:
if len(lt) != 0:
c = lt.pop()
if left.index(c) != right.index(i):
return False
else:
return False
if len(lt) != 0:
return False
else:
return True