Longest Substring with At Least K Repeating Characters
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
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) {
if (s == null || s.length() == 0) return 0;
if (k <= 1) return s.length();
if (s.length() < k) return 0;
int res = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) < k) {
sb.setCharAt(i, '#');
}
}
String[] partitions = sb.toString().split("#");
if (partitions.length == 1) {
return partitions[0].length();
}
for (String str : partitions) {
res = Math.max(res, longestSubstring(str, k));
}
return res;
}
}