1. 程式人生 > >Leetcode做題日記:20. 有效的括號 (PYTHON)

Leetcode做題日記:20. 有效的括號 (PYTHON)

給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字串,判斷字串是否有效。
有效字串需滿足:

左括號必須用相同型別的右括號閉合。
左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

示例 1:
輸入: “()”
輸出: true

示例 2:
輸入: “()[]{}”
輸出: true

示例 3:
輸入: “(]”
輸出: false

示例 4:
輸入: “([)]”
輸出: false

示例 5:
輸入: “{[]}”
輸出: true

        L=len(s)
        if L%2!=0:
            return
False LL=[] A={'(':0,'[':1,'{':2,')':3,']':4,'}':5} k=0 for i in s: LL.append(i) #棧 if k>=1 and len(LL)>=2: if A[LL[-2]]==A[LL[-1]]-3: #看是不是一對,是的話就是消消樂 LL.pop() LL.pop() k=
k+1 if LL==[]: return True else: return False #用棧的思想,刪除最裡面的最小的(),再依次往外刪除,比如([{}]()) #執行過程是:(,([,([{,([,(,((,(, , #在這裡我通過字典來判斷是否為一對() #添加了s不是偶數的判斷 #我第一次做的程式碼,我的想法是找到對稱分段,比如(),({}),{[]}等來判斷,可以 #很好判斷()[{}][] #但是當遇到{[()]()}這種不對稱的情況,就無能為力 L=len(s) A=
{'(':0,'[':1,'{':2} B={')':0,']':1,'}':2} st=0 end=1 i=1 if L==1: return False while st <L: if s[st] in A: a=A[s[st]] if end >=L: return False if s[end] in B: b=B[s[end]] if a==b: st=end+1 end=st+1 else: return False else: if end+i==L: return False while s[end+i] in A: i=i+1 if st+2*i+2>L: return False S=s[st:st+2*i+2] l=len(S) for j in range(i+1): if S[l-1-j]not in B or A[S[j]]!=B[S[l-1-j]]: return False st=st+2*i+2 end=st+1 else: return False i=1 return True