LeetCode--020--括號匹配
阿新 • • 發佈:2018-07-22
是否有效 exce 判斷 app bool elf stack 剔除 turn
題目描述:
給定一個只包括 ‘(‘
,‘)‘
,‘{‘
,‘}‘
,‘[‘
,‘]‘
的字符串,判斷字符串是否有效。
有效字符串需滿足:
- 左括號必須用相同類型的右括號閉合。
- 左括號必須以正確的順序閉合。
註意空字符串可被認為是有效字符串。
方法1:
遇到左括號壓入list中,遇到右括號時先判斷list是否為空,是則返回false,否則彈出一個字符與其進行比較,匹配則continue 否則返回false (32ms)
1 class Solution(object): 2 def isValid(self, s): 3 """ 4 :type s: str5 :rtype: bool 6 """ 7 lists = [] 8 i = 0 9 if len(s) == 1: 10 return False 11 elif len(s) == 0: 12 return True 13 while i < len(s): 14 c = s[i] 15 if c ==‘(‘ or c == ‘[‘ or c == ‘{‘: 16 #if i + 1 != len(s): 17 # if s[i+1] != ‘)‘ and s[i+1] != ‘]‘ and s[i+1] != ‘}‘: 18 # if c < s[i+1]: 19 # return False 20 #([])這種竟然算對,好吧 21 lists.append(c) 22 23 elifc == ‘)‘: 24 25 if len(lists) != 0: 26 t = lists.pop() 27 if t == ‘(‘: 28 i+=1 29 continue 30 else: 31 return False 32 else: 33 return False 34 elif c == ‘]‘: 35 36 if len(lists) != 0: 37 t = lists.pop() 38 if t == ‘[‘: 39 i+=1 40 continue 41 else: 42 return False 43 else: 44 return False 45 elif c == ‘}‘: 46 47 if len(lists) != 0: 48 t = lists.pop() 49 if t == ‘{‘: 50 i+=1 51 continue 52 else: 53 return False 54 else: 55 return False 56 i += 1 57 58 if len(lists) != 0: 59 return False 60 else: 61 return True
簡潔版:(28ms)
1 class Solution: 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 stack = [] 8 for c in s: 9 if c == ‘(‘ or c == ‘{‘ or c == ‘[‘: 10 stack.append(c) 11 elif not stack: 12 return False 13 elif c == ‘)‘ and stack.pop() != ‘(‘: 14 return False 15 elif c == ‘}‘ and stack.pop() != ‘{‘: 16 return False 17 elif c == ‘]‘ and stack.pop() != ‘[‘: 18 return False 19 return not stack
利用字典:(24ms)
1 class Solution(object): 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 pars = [None] 8 parmap = {‘)‘: ‘(‘, ‘}‘: ‘{‘, ‘]‘: ‘[‘} 9 for c in s: 10 if c in parmap: 11 if parmap[c] != pars.pop(): 12 return False 13 else: 14 pars.append(c) 15 return len(pars) == 1
時間最短:(20ms)
用拋出異常的方式把類似)()剔除
1 class Solution(object): 2 def isValid(self, s): 3 """ 4 :type s: str 5 :rtype: bool 6 """ 7 try: 8 stack = [] 9 for key in s : 10 if(key == ‘(‘ or key == ‘[‘ or key == ‘{‘): 11 stack.append(key) 12 else: 13 if((key == ‘)‘ and stack.pop() == ‘(‘) or 14 (key == ‘]‘ and stack.pop() == ‘[‘) or 15 (key == ‘}‘ and stack.pop() == ‘{‘)): 16 pass 17 else: 18 return False 19 if(len(stack) == 0): 20 return True 21 except IndexError: 22 return False 23 return False
2018-07-22 18:48:45
LeetCode--020--括號匹配