用 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