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
原文地址:https://www.cnblogs.com/zle1992/p/8469603.html
时间: 2024-10-27 19:55:41