Given a string, find the length of the longest substring T that contains at most K distinct characters.
For example, Given s = and “eceba”
k = 2,
T is "ECE" which it length is 3.
This problem is before that longest Substring with at the most two Distinct characters expansion, and that the solution of the problem of a settlement method two directly will be 2 K on the line, the specific explanation please refer to the previous blog:
Solution One:
classSolution { Public: intLengthoflongestsubstringkdistinct (stringSintk) {intres =0, left =0; Unordered_map<Char,int>m; for(inti =0; I < s.size (); ++i) {++M[s[i]]; while(M.size () >k) {if(--m[s[left]] = =0) M.erase (S[left]); ++Left ; } Res= Max (res, I-left +1); } returnRes; }};
For details, please refer to the previous blog longest Substring with at the most of the Distinct characters, see the code below:
Solution Two:
classSolution { Public: intLengthoflongestsubstringkdistinct (stringSintk) {intres =0, left =0; Unordered_map<Char,int>m; for(inti =0; I < s.size (); ++i) {m[s[i]]=i; while(M.size () >k) {if(M[s[left]] = =Left ) m.erase (S[left]); ++Left ; } Res= Max (res, I-left +1); } returnRes; }};
Similar topics:
Longest Substring with at the most of the Distinct characters
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Longest Substring with at the most k Distinct characters up to k different characters of the oldest string