题目链接:https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/#/description
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 = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
思路:先遍历整个string,并记录每个不同的character的出现次数。如果所有character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;如果有character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次递归,找到最大的返回值即可。
class Solution{
public:
int longestSubstring(string s,int k)
{
vector<int> bucket(26,0);
for(auto c:s)
bucket[c-'a']++;
char delim=NULL;
for(int i=0;i<26;i++)
{
if(bucket[i]>0 && bucket[i]<k)
{
delim=(char)(i+'a');
}
}
if(delim==NULL)
return (int)s.length();
vector<string> res;
int maxlen=0;
stringstream ss(s);
string g;
while(getline(ss,g,delim))
{
res.push_back(g);
}
for(auto str:res)
{
maxlen=max(maxlen,longestSubstring(str,k));
}
return maxlen;
}
};