20.?有效的括號(hào)
給定一個(gè)只包括?'(',')','{','}','[',']'的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號(hào)必須用相同類型的右括號(hào)閉合。
左括號(hào)必須以正確的順序閉合。
注意空字符串可被認(rèn)為是有效字符串。
示例 1:
輸入:"()"輸出:true
示例?2:
輸入:"()[]{}"輸出:true
示例?3:
輸入:"(]"輸出:false
示例?4:
輸入:"([)]"輸出:false
示例?5:
輸入:"{[]}"輸出:true
class Solution:
? ? dic_left =['(','{','[']
? ? dict_right = [')','}',']']
? ? def isValid(self, s):
? ? ? ? """
? ? ? ? :type s: str
? ? ? ? :rtype: bool
? ? ? ? """
? ? ? ? length = len(s)
? ? ? ? dict_content = []
? ? ? ? if length%2!=0:
? ? ? ? ? ? return False
? ? ? ? i=0
? ? ? ? while i< length:
? ? ? ? ? ? if s[i] in self.dic_left:
? ? ? ? ? ? ? ? dict_content.append(s[i])
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? if i==0:
? ? ? ? ? ? ? ? ? ? return False
? ? ? ? ? ? ? ? elif self.dic_left.index(dict_content[dict_content.__len__()-1])== self.dict_right.index(s[i]):
? ? ? ? ? ? ? ? ? ? dict_content.pop(dict_content.__len__()-1)
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? return False
? ? ? ? ? ? i+=1
? ? ? ? if dict_content.__len__()>0:
? ? ? ? ? ? return False
? ? ? ? return True
