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.
Solution
Divide and conquer, time O(n ^ 2), space O(n)
乍一看这道题完全没思路,只能想到O(n ^ 3)的暴力解法。用Two-pointer呢,也不知道该怎么移动。后来发现,用普通的分治思想就可以解决。
首先遍历arr,找到第一个illegal char的位置 x,然后将arr在x处分成两部分,然后递归解决即可。也算是DFS解法了。
For Example: bbcddefegaghfh and 2, so we shall dfs on "bb", "ddefeg", "ghfh", since a , c only appears1 for once.
class Solution {
public int longestSubstring(String s, int k) {
if (s == null || k < 1) {
return 0;
}
return dfs(s.toCharArray(), 0, s.length(), k);
}
public int dfs(char[] arr, int start, int end, int k) {
if (end - start < k) {
return 0;
}
int[] count = new int[26];
for (int i = start; i < end; ++i) {
++count[arr[i] - 'a'];
}
for (int i = 0; i < count.length; ++i) {
if (count[i] == 0 || count[i] >= k) {
continue;
}
// find the first illegal char between [start, end)
for (int j = start; j < end; ++j) {
if (arr[j] - 'a' != i) {
continue;
}
// split arr by the first illegal char
int left = dfs(arr, start, j, k);
int right = dfs(arr, j + 1, end, k);
return Math.max(left, right);
}
}
return end - start;
}
}