ฟังก์ชันนี้คืนดัชนี (index) ของตัวอักษรตัวแรกที่ปรากฏซ้ำในสตริง หากไม่มีตัวอักษรซ้ำจะคืน -1
ตัวอย่าง
// Input: 'Hello world, how are you' // Output: 2 (ตัวอักษร 'l' ตัวที่ 2 ใน 'Hello')
ตัวอย่างโค้ด
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));
การทำงาน
- ใช้
Mapเก็บคู่ตัวอักษร -> ดัชนีแรก - วนลูปตรวจสอบแต่ละตัวอักษร
- ถ้ามีใน Map แล้ว → คืนดัชนีที่บันทึกไว้
- ถ้ายังไม่มี → บันทึกดัชนีปัจจุบัน
ผลลัพธ์
2
Complexity: O(n) เวลา, O(k) พื้นที่ (k = จำนวนตัวอักษรที่ไม่ซ้ำ)