在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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志