20. 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
3、注意空字符串可被认为是有效字符串。

示例 1:
输入: "()"
输出: true

示例 2:
输入: "()[]{}"
输出: true


思路:栈。
 1 class Solution(object):
 2     def isValid(self, s):
 3         """
 4         :type s: str
 5         :rtype: bool
 6         """
 7         if s == "":
 8             return True
 9         # 用集合来模拟栈
10         listStr = list(s)
11         listLeft = ['(', '[', '{']
12         listRight = [')', ']', '}']
13         result = []
14         length = 0
15         if listStr[0] in listRight or listStr[len(listStr) - 1] in listLeft:
16             return False
17 
18         for num, ch in enumerate(listStr):
19             if ch in listLeft:
20                 result.append(ch)
21                 length += 1
22             elif ch in listRight:
23                 # 栈不为空才继续
24                 if length == 0:
25                     return False
26                 # 取出反括号在集合中的下标
27                 i = listRight.index(ch)
28                 if len(result) != 0 and result[-1] != listLeft[i]:
29                     return False
30                 else:
31                     result.pop()
32                     length -= 1
33 
34         if length != 0:
35             return False
36         else:
37             return True
38 
39 if __name__ == '__main__':
40     solution = Solution()
41     print(solution.isValid("()[]{}"))
42     print(solution.isValid("[])"))
43     print(solution.isValid("()"))
44     print(solution.isValid(""))

 

 
posted @ 2020-04-11 20:14  人间烟火地三鲜  阅读(100)  评论(0编辑  收藏  举报