python 有效的括號的實現程式碼示例
阿新 • • 發佈:2020-01-09
給定一個只包括 '(',')','{','}','[',']'的字串,判斷字串是否有效。
有效字串需滿足:
左括號必須用相同型別的右括號閉合。
左括號必須以正確的順序閉合。
注意空字串可被認為是有效字串。
示例 1:
輸入: "()"
輸出: true
示例2:
輸入: "()[]{}"
輸出: true
示例3:
輸入: "(]"
輸出: false
示例4:
輸入: "([)]"
輸出: false
示例5:
輸入: "{[]}"
輸出: true
注意此處所用程式碼為python3
class Solution: def pipei(self,m:str,c:str) -> bool: if m=='(' and c==')': return True elif m=='[' and c==']': return True elif m+c == '{}': return True else : return False def isValid(self,s: str) -> bool: lens = len(s) if lens == 0 : return True if s[0]==')' or s[0]==']' or s[0]=='}' : return False lis = [] lis.append(s[0]) for i in range(1,lens) : if len(lis) : tmp = lis.pop() if self.pipei(tmp,s[i]) : pass else : lis.append(tmp) lis.append(s[i]) else : lis.append(s[i]) if len(lis) : return False return True
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。