from collections import Counter
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
char_count = Counter()
max_length = start_index = 0
for i, char in enumerate(s):
char_count[char] += 1
while len(char_count) > k:
char_count[s[start_index]] -= 1
if char_count[s[start_index]] == 0:
del char_count[s[start_index]]
start_index += 1
max_length = max(max_length, i - start_index + 1)
return max_length