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

หาคำที่ซ้ำในสตริง - JavaScript

หาคำที่ปรากฏมากกว่า 1 ครั้งในสตริง คืนค่าเป็นสตริงรวมคำซ้ำ (ไม่ซ้ำกัน)

ตัวอย่าง

'big black bug bit a big black dog on his big black nose'
→ 'big black'

ตัวอย่างโค้ด

const str = 'big black bug bit a big black dog on his big black nose';

const findDuplicateWords = str => {
  const words = str.split(' ');
  const res = [];
  
  for (let i = 0; i < words.length; i++) {
    if (words.indexOf(words[i]) !== words.lastIndexOf(words[i])) {
      if (!res.includes(words[i])) {
        res.push(words[i]);
      }
    }
  }
  return res.join(' ');
};

console.log(findDuplicateWords(str));

ผลลัพธ์

big black

วิธีแบบ Map (มีประสิทธิภาพ O(n))

const findDuplicateWords = str => {
  const freq = new Map();
  for (const word of str.split(' ')) {
    freq.set(word, (freq.get(word) || 0) + 1);
  }
  return [...freq.entries()]
    .filter(([_, count]) => count > 1)
    .map(([word]) => word)
    .join(' ');
};

ใช้ Map นับความถี่ แล้วกรอง count > 1 เร็วกว่า indexOf/lastIndexOf มาก