Leetcode 395. Longest Substring with at Least K repeating characters C #

Source: Internet
Author: User

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every Character in T appears no less than K times.

Example 1:

input:s = "Aaabb", k = 3output:3the longest substring is "AAA", and as ' a ' is repeated 3 times.

Example 2:

input:s = "Ababbc", k = 2output:5the longest substring is "ababb", as ' a ' are repeated 2 times and ' B ' is repeated 3 times.

Solution: map all characters in string s to a Hash Map and store the count of characters as values. If all characters occur to than Ktimes, then return the whole string length as result; if not, find the least occured character and split the string by this char, then call this function recursive Ly To get the max length out of all substrings. return the max.
1  Public classSolution {2      Public intLongestsubstring (stringSintk) {3dictionary<Char,int> map =Newdictionary<Char,int>();4         if(string. IsNullOrEmpty (s))5         {6             return 0;7         }8         intL =s.length;9          for(intI=0; i<l; i++)Ten         { One             if(map. ContainsKey (S[i])) A             { -map[s[i]]++; -             } the             Else -             { -Map. ADD (S[i],1); -             } +         } -         CharMinkey=map. Aggregate (p, r) = P.value < R.value?p:r). Key; +         if(map[minkey]>=k) A         { at             returnl; -         } -         string[] splitted =S.split (minkey); -         intMax =0; -         foreach(stringNinchsplitted) -         { in             intm =longestsubstring (n,k); -             if(m>max) to             { +Max =m; -             } the         } *         returnMax; $         Panax Notoginseng     } -}

Leetcode 395. Longest Substring with at Least K repeating characters C #

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.