在JavaScript中使用至少n个重复字符查找最长的子字符串
我们需要编写一个JavaScript函数,该函数将字符串作为第一个参数,并将正整数n作为第二个参数。
该字符串可能包含一些重复的字符。该函数应从所有字符至少出现n次的原始字符串中找出并返回最长子字符串的长度。
例如-
如果输入字符串和数字为-
const str = 'kdkddj'; const num = 2;
那么输出应该是-
const output = 5;
因为所需的最长子字符串是'kdkdd'
示例
以下是代码-
const str = 'kdkddj';
const num = 2;
const longestSubstring = (str = '', num) => {
if(str.length < num){
return 0
};
const map = {}
for(let char of str) {
if(char in map){
map[char] += 1;
}else{
map[char] = 1;
}
}
const minChar = Object.keys(map).reduce((minKey, key) => map[key] <
map[minKey] ? key : minKey)
if(map[minChar] >= num){
return str.length;
};
substrings = str.split(minChar).filter((subs) =>subs.length>= num);
if(substrings.length == 0){
return 0;
};
let max = 0;
for(ss of substrings) {
max = Math.max(max, longestSubstring(ss, num))
};
return max;
};
console.log(longestSubstring(str, num));输出结果以下是控制台输出-
5