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

การสร้าง substring ทั้งหมดที่เป็นไปได้ของสตริงใน JavaScript

บทความนี้สาธิตฟังก์ชันสร้างอาร์เรย์ที่มี substring ทั้งหมด (contiguous และ non-contiguous) ของสตริงที่กำหนด

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

const str = 'Delhi';

const allCombinations = (str1 = '') => {
  const arr = [];
  for (let x = 0, y = 1; x < str1.length; x++, y++) {
    arr[x] = str1.substring(x, y);
  }
  const combination = [];
  let temp = "";
  let len = Math.pow(2, arr.length);
  for (let i = 0; i < len; i++) {
    temp = "";
    for (let j = 0; j < arr.length; j++) {
      if ((i & Math.pow(2, j))) {
        temp += arr[j];
      }
    }
    if (temp !== "") {
      combination.push(temp);
    }
  }
  return combination;
};

console.log(allCombinations(str));

ผลลัพธ์

[
  'D', 'e', 'De', 'l',
  'Dl', 'el', 'Del', 'h',
  'Dh', 'eh', 'Deh', 'lh',
  'Dlh', 'elh', 'Delh', 'i',
  'Di', 'ei', 'Dei', 'li',
  'Dli', 'eli', 'Deli', 'hi',
  'Dhi', 'ehi', 'Dehi', 'lhi',
  'Dlhi', 'elhi', 'Delhi'
]

คำอธิบาย

อัลกอริทึมใช้ bitmask: แยกตัวอักษรแต่ละตัวเป็นอาร์เรย์ แล้วสร้าง combination ทั้ง 2^n - 1 แบบ (ยกเว้นชุดว่าง) โดยใช้ bitwise AND ตรวจสอบ bit ที่ j ของ i

หมายเหตุ: ผลลัพธ์รวม subsequence (ไม่จำเป็นติดกัน) ไม่ใช่แค่ substring ที่ติดกัน