เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง ฟังก์ชันควรหาและคืนค่าความยาวของสตริงย่อยที่ยาวที่สุดที่ถูกแซนด์วิชระหว่างตัวอักษรเดียวกันสองตัว
เช่น ถ้าสตริงอินพุตคือ:
const str = 'avbghvh';
ผลลัพธ์ควรเป็น:
const output = 3;
เพราะสตริงย่อยที่ต้องการที่ยาวที่สุดคือ 'bgh' ระหว่าง v สองตัว
ตัวอย่าง
const str = 'avbghvh';
const longestSub = (str = '') => {
const map = new Map();
let max = -1;
for(let i = 0; i < str.length; i++){
if(map.has(str.charAt(i))){
max = Math.max(max, i - map.get(str.charAt(i)) - 1);
}else{
map.set(str.charAt(i), i);
};
};
return max;
};
console.log(longestSub(str));
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังนี้:
3