เราจำเป็นต้องเขียนฟังก์ชัน 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