longest substrinct with at most k distinct characters

🏠

https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/

Credit: lenchen1112

 1import collections
 2
 3class Solution:
 4    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
 5        i, max_len, index_map = 0, 0, collections.OrderedDict()
 6        for j, c in enumerate(s, 1):
 7            index_map[c] = j
 8            index_map.move_to_end(c)
 9            if len(index_map) > k:
10                _, i = index_map.popitem(last=False)
11            max_len = max(max_len, j - i)
12        return max_len
13
14print(Solution().lengthOfLongestSubstringKDistinct("a", 2))