Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created October 18, 2018 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/dcb475a7a34c689afc3dea771656f098 to your computer and use it in GitHub Desktop.
Save yokolet/dcb475a7a34c689afc3dea771656f098 to your computer and use it in GitHub Desktop.
Longest Substring with At Most K Distinct Characters
"""
Description:
Given a string, find the length of the longest substring T that contains at most k
distinct characters.
Examples:
Input: s = "eceba", k = 2
Output: 3 -- 'ece' is the longest
Input: s = "aa", k = 1
Output: 2 -- 'aa' is the longest
"""
def lengthOfLongestSubstringKDistinct(s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
ret, left = 0, 0
lastIndex = {}
for i, char in enumerate(s):
lastIndex[char] = i
if len(lastIndex) > k:
left = min(lastIndex.values())
del lastIndex[s[left]]
left += 1
if i - left + 1 > ret:
ret = i - left + 1
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment