就用stack掃過去 要檢查一下stk.empty() 不然會吃index out of range def minLength(self, s: str) -> int: stk = [] for c in s: if c=='B' and len(stk)>0 and stk[-1]=='A': stk.pop() elif c=='D' and len(stk)>0 and stk[-1]=='C': stk.pop() else: stk.append(c) return len(stk)