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

นับคำที่ซ้ำ 2 ครั้งในสตริง - JavaScript

นับจำนวนคำที่ปรากฏ ซ้ำกัน 2 ครั้งพอดี ในสตริง

ตัวอย่าง

'car bus jeep car jeep bus motorbike truck'
car: 2, bus: 2, jeep: 2 → นับ = 3 คำ

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

const str = 'car bus jeep car jeep bus motorbike truck';

const countRepetitive = str => {
  const words = str.split(' ');
  let count = 0;
  
  for (let i = 0; i < words.length; i++) {
    if (i === words.lastIndexOf(words[i])) continue;
    count++;
  }
  return count;
};

console.log(countRepetitive(str));

ผลลัพธ์

3

หมายเหตุเกี่ยวกับ Logic

โค้ดต้นฉบับนับ "คำที่มี duplicate" (index ≠ lastIndex) ไม่ใช่ "คำที่ปรากฏ 2 ครั้งพอดี"

ถ้าคำใดปรากฏ 3 ครั้ง จะถูกนับ 2 ครั้ง (index 0 และ 1)

เวอร์ชันนับ "พอดี 2 ครั้ง" (Exactly Twice)

const countExactlyTwice = str => {
  const freq = new Map();
  for (const w of str.split(' ')) freq.set(w, (freq.get(w) || 0) + 1);
  return [...freq.values()].filter(c => c === 2).length;
};