159. Longest Substring with At Most Two Distinct Characters

sliding window,窗口大小会变化,重点还是在何时更新左指针。count 用来记录当前有多少种不同的字符,只要当前进入窗口的字符使 count 不满足题目条件,我们就移动左指针让 count 满足条件,一直维护一个符合条件的window。

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        res = 0
        freq = dict()
        count = 0
        
        l, r = 0, 0
        while r < len(s):
            # 把右指针字符加进统计
            freq[s[r]] = freq.get(s[r], 0) + 1
            
            # 如果s[r]是new distinct character,就计数
            if freq[s[r]] == 1: count += 1
            # 当计数超过2时,触发左指针移动,直到计数不再大于2
            while count > 2:
                # 左指针字符的统计要-1
                freq[s[l]] -= 1
                # 如果移出的左指针字符已经是该字符最后一个,计数-1
                if freq[s[l]] == 0: count -= 1
                l += 1
            
            # 如果当前window更长,就更新结果
            res = max(res, r+1-l)
            
            r += 1
        
            
        return len(s) if len(s)<=2 else res

Last updated

Was this helpful?