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.
Analysis:
Given a string s, find out all chars that are invalid (i.e., count < k). The longest substring must reside in one of the substrings divided by those invalid chars. We find out all those possible substrings and recursively address each of them.
NOTE: repeatedly using s.charAt() is actually very slow. So we convert the string to charArray in the first place
public class Solution {
public int longestSubstring(String s, int k) {
return longestSubstring(s.toCharArray(), 0, s.length()-1, k);
} public int longestSubstring(char[] arr, int start, int end, int k) {
if (end < start) return 0;
if (end-start+1 < k) return 0;
int[] count = new int[26];
for (int i=start; i<=end; i++) {
count[arr[i]-'a']++;
}
for (int i=0; i<26; i++) {
if (count[i] == 0) continue;
if (count[i] < k) {
int j = start;
for (; j<=end; j++) {
if (arr[j] == (char)('a'+i)) break;
}
int left = longestSubstring(arr, start, j-1, k);
int right = longestSubstring(arr, j+1, end, k);
return Math.max(left, right);
}
}
return end-start+1;
}
}