就用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)