LeetCode有效的括號字串
阿新 • • 發佈:2020-09-12
題目描述:
示例:
知識點:
一:一連串的判斷
7 class Solution: 8 def isValid(self, s: str) -> bool: 9 temp = [] 10 11 for item in s: 12 if item in ['(', '{', '[']: 13 temp.append(item) 14 else: 15 if len(temp) != 0: 16 c = temp.pop()17 if c == '(' and item != ')': 18 return False 19 if c == '[' and item != ']': 20 return False 21 if c == '{' and item != '}': 22 return False 23 else:24 return False 25 if len(temp) != 0: 26 return False 27 else: 28 return True
二:字典的使用
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 dic = {'(':')', '{':'}', '[':']'} 4 sta = [] 5 for c in s:6 if c in ['(', '[', '{']: 7 sta.append(c) 8 elif sta: 9 if c != dic[sta.pop()]: 10 return False 11 else: 12 return False 13 return True if len(sta) == 0 else False
四:字串的妙用
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 while '()' in s or '[]' in s or '{}' in s: 4 s=s.replace('()', '').replace('[]', '').replace('{}', '') 5 return True if len(s) == 0 else False
三:衛兵的使用
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 dic = {'(':')', '{':'}', '[':']', '?':'?'} 4 sta = ['?'] 5 for c in s: 6 if c in ['(', '[', '{']: 7 sta.append(c) 8 elif c != dic[sta.pop()]: 9 return False 10 return True if len(sta) == 1 else False