给你一个字符串 s
和一个整数 k
,请你找出 s
中的最长子串, 要求该子串中的每一字符出现次数都不少于 k
。返回这一子串的长度。
示例 1:
输入:s = "aaabb", k = 3 输出:3 解释:最长子串为 "aaa" ,其中 'a' 重复了 3 次。
示例 2:
输入:s = "ababbc", k = 2 输出:5 解释:最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
提示:
1 <= s.length <= 104
s
仅由小写英文字母组成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;
}
}