题目
https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/
思路
见代码
代码
/**
* @param {string} s
* @param {number} k
* @return {number}
*/
var longestSubstring = function(s, k) {
let result = 0;
//从包含的字符种类入手,假设最长子串只包含一种字符
for (let num = 1; num < 27; num++){
let cnt = Array(26);//创建一个数组储存每个字母对应的次数
cnt.fill(0,0,27);//初始化为0
let kind = 0; //目前子串中的字符种类
let n = 0; //目前子串中满足要求的字符种类
for (let i = 0, j = 0; j < s.length; j++){
let pos =s[j].charCodeAt() -'a'.charCodeAt();
cnt[pos]++;
//满足条件的字符数种类加一
if (cnt[pos] === k){
n++;
}
//为1时,说明之前没有出现过这个种类的字符
if (cnt[pos] === 1){
kind++;
}
//种类数量超了,需要退一种字符
while (kind > num){
pos = s[i++].charCodeAt() -'a'.charCodeAt();
cnt[pos]--;
//说明退出的这个字符导致满足子串包含的字符种类数减少了
if (cnt[pos] === 0){
kind--;
}
//说明退出的这个字符导致满足条件的字符种类数减少了
if (cnt[pos] === k - 1){
n--;
}
}
//如果子串中包含的字符种类数等于符合要求的字符种类数,说明全都符合,此时子串符合要求
if (n === kind){
result = Math.max(result, j - i + 1);
}
}
}
return result;
};