395. Longest Substring with At Least K Repeating Characters
- Total Accepted: 2080
- Total Submissions: 6509
- Difficulty: Medium
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.
public static int longestSubstring(String s, int k) {
int[] arr = new int[26];
Arrays.fill(arr, 0);
char[] aStr = s.toCharArray();
for(int i = 0; i < aStr.length;i++){
arr[aStr[i] - 'a'] ++;
}
StringBuilder strB = new StringBuilder("");
boolean flag = true;
for(int i = 0; i < 26;i++){
if(arr[i] > 0 && arr[i] < k){
if(flag){
strB.append((char)(i+'a'));
flag = false;
}else{
strB.append("|"+(char)(i+'a'));
}
}
}
if(strB.length() >0){
String[] strs = s.split(strB.toString());
int cnt = 0;
int ans = 0;
for(String str :strs){
cnt = longestSubstring(str, k);
if(cnt > ans){
ans = cnt;
}
}
return ans;
}else{
return s.length();
}
}