เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและส่งคืนดัชนีของอักขระตัวแรกที่ปรากฏสองครั้งในสตริง
หากไม่มีอักขระดังกล่าว เราควรคืนค่า -1 ต่อไปนี้เป็นสตริงของเรา -
const str = 'Hello world, how are you';
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'Hello world, how are you';
const firstRepeating = str => {
const map = new Map();
for(let i = 0; i < str.length; i++){
if(map.has(str[i])){
return map.get(str[i]);
};
map.set(str[i], i);
};
return -1;
};
console.log(firstRepeating(str)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์ในคอนโซล -
2