Created
June 14, 2019 15:04
-
-
Save yangpeng-chn/f7f6179c572f42a4ea9f7dc205455ff6 to your computer and use it in GitHub Desktop.
This file contains 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
int longestSubstringKDistinct(string str, int k){ | |
int start = 0, res = 0; | |
unordered_map<char, int> um; | |
for (int i = 0; i < str.size(); ++i) | |
{ | |
um[str[i]]++; | |
while(um.size() > k){ | |
char left = str[start]; | |
if(--um[left] == 0) | |
um.erase(left); | |
start++; | |
} | |
res = max(res, i - start + 1); //no need to put in while block as if the size is k, the res will be updated | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment