340. Longest Substring with At Most K Distinct Characters (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class Solution(object):
    def lengthOfLongestSubstringKDistinct(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        i = j = 0
        h = {}
        result = 0
        while j < len(s):
            h[s[j]] = h.get(s[j], 0) + 1
            if len(h) > k:
                result = max(result, j - i)
                while True:
                    val = s[i]
                    h[val] -= 1
                    i += 1
                    if h[val] == 0:
                        del h[val]
                        break
            j += 1
        result = max(result, j - i)
        return result