用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP