继续搬https://zhuanlan.zhihu.com/p/36414513
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
这个刚开始想的太复杂了,大至记录下思考过程:
1 .检查是否空字符串
2. 检查len是否偶数,否则肯定不成对。
3. 检查首尾括号的开口方向
4. 从中间位置二分,检查两边是否能组对。这个实际上有点麻烦,因为除了检查左右对比还需要检查分开的两个子串。
5. 参考论坛贴子后,决定采用stack的思路。简单理解就是,前进后出的原则给左括号配对。
扫描二维码关注公众号,回复:
2230721 查看本文章
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
str_dict = {')':'(',']':'[','}':'{'}
stack = []
if len(s) == 0: #判断是否空串
return True
#检查是否成对以及是否首尾括号方向正确
if len(s)%2 != 0 or s[0] in str_dict.keys() or s[-1] in str_dict.values():
return False
for i in range(len(s)):
if s[i] in str_dict.values() and i < len(s):
stack.append(s[i])
elif str_dict[s[i]] != stack[-1]:
return False
else:
del stack[-1]
return True