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.
自己想了两种方法但都在一个很长的字符串上超时了,
首先是递归方法,先贪心算法找到从开始字母计算的最长字符串,然后将后面的字符串进行递归,返回的结果进行对比紧返回最大的那个值。
class Solution {
public:
int longestSubstring(string s, int k) {
int size = s.size();
if(size==0) return 0;
vector<int> v(26,0);
int flag=0;
int max=0;
for(int i = 0;i < size;i++){
v[s[i]-'a']++;
flag=1;
for(int j=0;j<26;j++){
if(v[j]<k&&v[j]>0) flag=0;
}
if(flag==1) max=i+1;
}
//cout<<s<<' '<<max<<' '<<s.substr(max,size-max)<<endl;
int ma = Solution::longestSubstring(s.substr(max>0?max:1,size-1),k);
return ma>max ? ma:max;
}
};
也是贪心算法,每一遍循环在上一次循环得到的起点开始,得到最长字符串后,将下一位置也即下一循环的起点算出。
class Solution {
public:
int longestSubstring(string s, int k) {
int size = s.size();
if(size==0) return 0;
vector<int> v(26,0);
int flag=0;
int max=0;
int now=0;
int now_i=0;
int i = 0;
while(now<=size){
now_i=0;
for(i = now;i < size;i++){
v[s[i]-'a']++;
flag=1;
for(int j=0;j<26;j++){
if(v[j]<k&&v[j]>0) flag=0;
}
if(flag==1){
now_i=i;
max=i+1-now>max ? i+1-now : max;
}
}
if(now_i!=0&&now_i!=now) now=now_i++;
else now++;
for(int j=0;j<26;j++){
v[j]=0;
}
}
return max;
}
};