生成字串所有可能組合的 JavaScript 函式


我們需要編寫一個 JavaScript 函式,該函式接收一個字串作為唯一引數。該函式應生成一個字串陣列,其中包含陣列中存在的所有可能的連續子字串。

示例

以下為程式碼 −

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'
]

更新時間:11-12-2020

673 次瀏覽

開啟 事業

獲得文憑,完成課程

開始
廣告
© . All rights reserved.