思路如下:
1、求子串问题,可以考虑采用递归拆分子串的分治算法,将字符串拆分求得符合要求的最长字串
2、先定义一个int数组存储26个字母出现的次数,然后使用头尾指针从两端开始遍历,如果两端的指针对应的字符次数小于k,则指针向中间移动。
3、第2步得到一个新的子串,从头遍历,如果发现有一个字符出现次数小于k,则以此字符为分界对子串进行拆分递归。
class Solution {
public int longestSubstring(String s, int k) {
//边界条件
if(s.length()==0||k>s.length()){
return 0;
}
return count(s.toCharArray(),k,0,s.length()-1);
}
public int count(char[] cs,int k,int start,int end){
int[] times=new int[26];
//对以start开始到end的cs子串进行次数记录
for(int i=start;i<=end;i++){
times[cs[i]-'a']++;
}
//如果start对应的字母出现次数小于k,则右移
while(times[cs[start]-'a']<k&&&&start<end){
++start;
}
//如果start对应的字母出现次数小于k,则左移
while(times[cs[end]-'a']<k&&&&start<end){
--end;
}
//如果长度小于k,则没有符合的子串,返回长度0
if(end-start+1<k){
return 0;
}
//查找start到end的子串中的分割点,即第一个字母出现次数小于k的下标i,拆分递归
for(int i=start;i<=end;i++){
if(times[cs[i]-'a']<k){
return Math.max(count(cs,k,start,i-1),count(cs,k,i+1,end));
}
}
return end-start+1;
}
}
原题地址:
395. 至少有K个重复字符的最长子串