Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาดัชนีของตัวอักษรซ้ำแรกในสตริง - JavaScript

ฟังก์ชันนี้คืนดัชนี (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));

การทำงาน

  1. ใช้ Map เก็บคู่ ตัวอักษร -> ดัชนีแรก
  2. วนลูปตรวจสอบแต่ละตัวอักษร
  3. ถ้ามีใน Map แล้ว → คืนดัชนีที่บันทึกไว้
  4. ถ้ายังไม่มี → บันทึกดัชนีปัจจุบัน

ผลลัพธ์

2

Complexity: O(n) เวลา, O(k) พื้นที่ (k = จำนวนตัวอักษรที่ไม่ซ้ำ)