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

การหาตัวอักษรที่ซ้ำกันระหว่างสองสตริง - JavaScript

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

ตัวอย่าง

str1 = 'Hey There!!, how are you'
str2 = 'Can this be a special string'
// Output: 'e here h are' (ตัวอักษรที่ซ้ำกัน ตามลำดับใน str1)

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

const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';

const commonString = (str1, str2) => {
  let res = '';
  for (let i = 0; i < str1.length; i++) {
    if (!str2.includes(str1[i])) continue;
    res += str1[i];
  }
  return res;
};

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

การทำงาน

  • วนลูปทุกตัวอักษรใน str1
  • ถ้ามีใน str2 (includes) → เพิ่มในผลลัพธ์
  • รวมตัวซ้ำ (ถ้า str1 มี 'e' 3 ตัว และ str2 มี 'e' → ได้ 'eee')

ผลลัพธ์

e here h are

ปรับปรุง: ใช้ Set ของ str2 เพื่อ O(1) lookup แทน O(n) ของ includes