在 JavaScript 中找到兩個陣列中的公共串


我們需要編寫一個 JavaScript 函式,該函式接收兩個字面量陣列,我們稱它們為 arr1 和 arr2。

該函式應找到陣列中字面量的最長公共串。該函式最終應返回這些字面量的陣列。

例如 −

如果輸入陣列為 −

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];

則輸出陣列應為 −

const output = ['b', 'c', 'd'];

示例

程式碼如下 −

const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
const longestCommonSubsequence = (arr1 = [], arr2 = []) => {
   let str1 = arr1.join('');
   let str2 = arr2.join('');
   const arr = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
   for (let j = 0; j <= str1.length; j += 1) {
      arr[0][j] = 0;
   }
   for (let i = 0; i <= str2.length; i += 1) {
      arr[i][0] = 0;
   }
   for (let i = 1; i <= str2.length; i += 1) {
      for (let j = 1; j <= str1.length; j += 1) {
         if (str1[j - 1] === str2[i - 1]) {
            arr[i][j] = arr[i - 1][j - 1] + 1;
         } else {
            arr[i][j] = Math.max(
               arr[i - 1][j],
               arr[i][j - 1],
            );
         }
      }
   }
   if (!arr[str2.length][str1.length]) {
      return [''];
   }
   const res = [];
   let j = str1.length;
   let i = str2.length;
   while (j > 0 || i > 0) {
      if (str1[j - 1] === str2[i - 1]) {
         res.unshift(str1[j - 1]);
         j -= 1;
         i -= 1;
      }
      else if (arr[i][j] === arr[i][j - 1]) {
         j -= 1;
      }
      else {
         i -= 1;
      }
   }
   return res;
};
console.log(longestCommonSubsequence(arr1, arr2));

輸出

控制檯上的輸出如下 −

['b', 'c', 'd']

更新於: 11-Dec-2020

159 次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.