Created
October 18, 2018 20:21
-
-
Save yokolet/dcb475a7a34c689afc3dea771656f098 to your computer and use it in GitHub Desktop.
Longest Substring with At Most K Distinct Characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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