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

การนับตัวอักษรที่ซ้ำในสตริง (Redundant Characters) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีนับจำนวนตัวอักษรที่ซ้ำ (Redundant Characters) ในสตริง นับเป็นจำนวนครั้งที่เกินครั้งแรก

ตัวอย่าง

'abcde'     -> 0 (ไม่มีซ้ำ)
'aaacbfsc'  -> 3 (a ซ้ำ 2 ครั้งเพิ่ม, c ซ้ำ 1 ครั้งเพิ่ม = 3)

การนำไปใช้

const countRedundant = (str) => {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    // ถ้า Index นี้ไม่ใช่ครั้งสุดท้ายของตัวอักษรนี้ -> ซ้ำ
    if (i !== str.lastIndexOf(str[i])) {
      count++;
    }
  }
  return count;
};

console.log(countRedundant('aaacbfsc')); // 3

ผลลัพธ์

3

วิธีการทันสมัย (Frequency Map)

const countRedundantModern = (str) => {
  const freq = [...str].reduce((acc, c) => (acc[c] = (acc[c] || 0) + 1, acc), {});
  return Object.values(freq).reduce((sum, v) => sum + Math.max(0, v - 1), 0);
};

// หรือ
const countRedundantSimple = (str) => 
  str.length - new Set(str).size;

การแยก: Unique Characters vs Duplicate Count

const charStats = (str) => {
  const freq = [...str].reduce((acc, c) => (acc[c] = (acc[c] || 0) + 1, acc), {});
  const unique = Object.keys(freq).length;
  const total = str.length;
  const duplicates = total - unique;
  const redundant = Object.values(freq).reduce((s, v) => s + Math.max(0, v - 1), 0);
  
  return { unique, total, duplicates, redundant, freq };
};

console.log(charStats('aaacbfsc'));
// { unique: 5, total: 8, duplicates: 3, redundant: 3, freq: {a:3, c:2, b:1, f:1, s:1} }

การประยุกต์ใช้

  • String Compression Analysis
  • Password Strength: Penalize Repeated Characters
  • Data Quality: Detect Low Entropy Strings
  • Plagiarism: Repeated Phrases

ข้อควรระวัง

  • Case Sensitivity: 'A' != 'a'
  • Unicode: ใช้ [...str] สำหรับ Emoji/Thai
  • Whitespace: นับ Space ด้วยหรือไม่