[Leetcode] Longest Substring with at the most k Distinct characters up to k different characters of the oldest string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.