Skip to content
Gallery
Algoschool
Share
Explore
Level 1

icon picker
Sliding window problems

from collections import defaultdict

class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
l = 0
m = defaultdict(int)
max_len = 0
for r in range(len(s)):
cur = s[r]
m[cur] += 1
while len(m) > k:
m[s[l]] -= 1
if m[s[l]] == 0:
del m[s[l]]
l += 1
max_len = max(max_len, r - l + 1)
return max_len
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.