Given a string s
and an integer k
, return the length of the longest substring of s
such that the frequency of each character in this substring is greater than or equal to k
.
Example 1:
Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Constraints:
1 <= s.length <= 104
s
consists of only lowercase English letters.1 <= k <= 105
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
n = len(s)
maxLength = 0
for i in range(1, 27):
counter = dict()
left = 0
right = 0
unique = 0
kCount = 0
while right < n:
if unique <= i:
r = s[right]
counter[r] = counter.get(r, 0) + 1
if counter[r] == 1:
unique += 1
if counter[r] == k:
kCount += 1
right += 1
else:
l = s[left]
counter[l] = counter.get(l, 0) - 1
if counter[l] == 0:
unique -= 1
if counter[l] == k - 1:
kCount -= 1
left += 1
if unique == i and kCount == i:
maxLength = max(maxLength, right - left)
return maxLength
class Solution {
public int longestSubstring(String s, int k) {
int maxLength = 0;
int n = s.length();
for (int i = 1; i < 27; i++) {
Map<Character, Integer> counter = new HashMap<>();
int left = 0;
int right = 0;
int unique = 0;
int kCount = 0;
while (right < n) {
if (unique <= i) {
char r = s.charAt(right);
counter.put(r, counter.getOrDefault(r, 0) + 1);
if (counter.get(r) == 1) {
unique += 1;
}
if (counter.get(r) == k) {
kCount += 1;
}
right += 1;
} else {
char l = s.charAt(left);
counter.put(l, counter.getOrDefault(l, 2) - 1);
if (counter.get(l) == 0) {
unique -= 1;
}
if (counter.get(l) == k - 1) {
kCount -= 1;
}
left += 1;
}
if (unique == i && kCount == i) {
maxLength = Math.max(maxLength, right - left);
}
}
}
return maxLength;
}
}