20. Valid Parentheses(括號匹配,用桟)
阿新 • • 發佈:2018-02-25
char val solution 如果 close nth fix body -c
Given a string containing just the characters
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 ==[]: #桟為空,沒有匹配的 14return 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(括號匹配,用桟)