A simple variation to "Longest Substring with At Most Two Distinct Characters". A typical sliding window problem.
class Solution { public: int lengthOfLongestSubstringKDistinct(string s, int k) { unordered_map<char, unsigned> hm; int ret = 0, start = 0; for (int i = 0; i < s.length(); i++) { hm[s[i]]++; if (hm.size() <= k) { ret = std::max(ret, i - start + 1); } else { while (start < i && hm.size() > k) { char nc = s[start]; if (hm[nc] == 1) hm.erase(nc); else hm[nc]--; start++; } } } return ret; } };