Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created June 14, 2019 15:04
Show Gist options
  • Save yangpeng-chn/f7f6179c572f42a4ea9f7dc205455ff6 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/f7f6179c572f42a4ea9f7dc205455ff6 to your computer and use it in GitHub Desktop.
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