题目描述
找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
样例
输入:
s = "aaabb", k = 3
输出:
3
最长子串为 "aaa" ,其中 'a' 重复了 3 次。
算法
(枚举 + 双指针)
时间复杂度
O ( 26 ∗ n ) O(26 * n) O(26∗n)
参考文献
Java 代码
class Solution {
int[] word = new int [26];
int K, x, y;
// x 记录当前窗口中不相同的字母个数
// y 当前窗口中满足条件的字母个数
public void clear() {
for (int i = 0; i < 26; i ++ )
word[i] = 0;
}
public void add(char c) {
int idx = c - 'a';
if (word[idx] == 0) x ++ ;
word[idx] ++ ;
if (word[idx] == K) y ++ ;
}
public void del(char c) {
int idx = c - 'a';
if (word[idx] == K) y -- ;
word[idx] -- ;
if (word[idx] == 0) x -- ;
}
public int longestSubstring(String s, int _K) {
K = _K;
int res = 0;
for (int k = 1; k <= 26; k ++ ) {
clear();
x = 0;
y = 0;
for (int i = 0, j = 0; i < s.length(); i ++ ) {
add(s.charAt(i));
while (x > k) del(s.charAt(j ++ ));
if (x == y) res = Math.max(res, i - j + 1);
}
}
return res;
}
}