题目
给定一个字符串,给定一个数字k,找这个字符串里的最大子串的长度,子串满足的条件是:里面的每一个字母都出现了至少k次。
例如:
Input: s = "ababbc", k = 2 Output: 5 The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
思路:递归
- 用一个哈希表看一下这个字符串哪些字符不符合,如果所有字母都符合,就返回长度
- 把不符合的字符都标出来位置
- 对每一片连续的充满了符合的字母的子串进行递归,把每一片的结果都存下来,返回最长的那个
程序:
public class Solution {
public int longestSubstring(String s, int k) {
char[] str = s.toCharArray();
return findlongest(0, str.length, str, k);
}
public int findlongest(int start, int end, char[] str, int k) {
if(end - start < k) return 0;
int[] index = new int[str.length];
//store the times each character appears
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
for(int i = start; i < end; i++) {
Integer tmp = count.get(str[i]);
count.put(str[i], (tmp == null) ? 1 : tmp+1);
}
//judge whether the string obey the rule
boolean flag = true;
for(int i = start; i < end; i++) {
//store the position where the illegal characters locate
if(count.get(str[i]) < k) {index[i] = -1; flag = false;}
}
//if obey the rule, return the length
if(flag) return (end - start);
//if not, find each contiuous 0 in the index, recursive find each substring len,
//and store each lenth in the array len[]
int[] len = new int[end - start + 1];
int sta = start;
int cnt = 0;
int pos = 0;
for(int i = start; i < end; i++) {
if(index[i] == -1 ) {
len[pos++] = findlongest(sta, sta+cnt, str, k);
cnt = 0;
sta = i+1;
} else
cnt++;
}
len[pos++] = findlongest(sta, end, str, k);
//return the max number in len[]
int max = 0;
for(int i = 0; i < pos; i++) {
if(len[i] > max) max = len[i];
}
return max;
}
}