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.

 

 1 class Solution:
 2     def isValid(self, s):
 3         """
 4         :type s: str
 5         :rtype: bool
 6         """
 7         stack = []
 8         d={'(':')','[':']','{':'}'}
 9         for i in s:
10             if i in d.keys():#遇到左括号 压桟
11                 stack.append(i)
12             else: #遇到右括号
13                 if stack ==[]:  #桟为空,没有匹配的
14                     return False
15                 else:
16                     if i==d[stack[-1]] : #如果匹配上,弹桟
17                         stack.pop()
18                     else:
19                         return False #没有匹配上
20         return stack==[] #如果遍历完之后桟为空,则全部匹配
21                 
22         
23         

 

相关文章:

  • 2022-02-09
  • 2021-07-25
  • 2021-09-08
  • 2021-06-28
  • 2021-10-21
  • 2021-04-07
  • 2021-04-12
  • 2021-05-22
猜你喜欢
  • 2022-12-23
  • 2022-02-14
  • 2021-08-10
  • 2022-12-23
  • 2021-08-10
  • 2021-10-09
  • 2021-10-17
相关资源
相似解决方案