使用 JavaScript 檢查字串是否是由陣列中的字串組合而成


我們需要編寫一個 JavaScript 函式,該函式將一個字串陣列作為第一個引數,將一個字串作為第二個引數。

該函式應檢查由第二個引數指定的字串是否可以透過以任何可能的方式組合陣列的字串來形成。

例如,如果輸入陣列為

const arr = ["for","car","keys","forth"];

而字串為

const str = "forthcarkeys";

則輸出應為真,因為該字串是陣列中索引為 3、1 和 2 的元素的組合。

範例

程式碼如下

const arr = ["for","car","keys","forth"];
const str = "forthcarkeys";
const checkPossibility = (str = '', arr = []) => {
   let possibilities = arr.reduce(function (r, a) {
      let p = str.indexOf(a);
      while (p !== −1) {
         r.push({ word: a, position: p });
         p = str.indexOf(a, p + 1);
      }
      return r;
   }, []);
   const findRecursively = (i, t) => {
      let s = t.slice(), j;
      if (i === possibilities.length) {
         return !t.join('');
      }
      if (possibilities[i].word.split('').every(function (c, j) {
         return
         s[j + possibilities[i].position] !== ''; })) {
         for (j = 0; j < possibilities[i].word.length; j++) {
            s[j + possibilities[i].position] = '';
         }
      }
      return findRecursively(i + 1, s) || findRecursively(i + 1, t);
   }
   return findRecursively(0, str.split(''));
};
console.log(checkPossibility(str, arr));

輸出

控制檯中的輸出為

true

更新於: 2020 年 11 月 24 日

131 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.