首页 > 其他 > 详细

20. Valid Parentheses(括号匹配,用桟)

时间:2018-02-25 16:48:14      阅读:186      评论:0      收藏:0      [点我收藏+]

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         

 

20. Valid Parentheses(括号匹配,用桟)

原文:https://www.cnblogs.com/zle1992/p/8469603.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!