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 #