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

การนับจำนวนตัวอักษรที่ซ้ำกันในสองสตริง (Common Character Count) ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับสองสตริง นับจำนวนตัวอักษรที่ซ้ำกัน (common characters) โดยนับความถี่ด้วย (ถ้าตัวอักษรปรากฏ 2 ครั้งในทั้งสองสตริง นับเป็น 2)

ตัวอย่าง: 'aabbcc' และ 'adcaa' → ตัวอักษรซ้ำ: a (2 ครั้ง), a (อีก 1 ครั้ง), c (1 ครั้ง) → รวม 3

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

const str1 = 'aabbcc';
const str2 = 'adcaa';

const commonCharacterCount = (str1 = '', str2 = '') => {
  let count = 0;
  str1 = str1.split('');
  str2 = str2.split('');
  str1.forEach(e => {
    if (str2.includes(e)) { count++; str2.splice(str2.indexOf(e), 1); }
  });
  return count;
};

console.log(commonCharacterCount(str1, str2));

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

3