在JavaScript中找到两个字符串之间最长的公共连续子字符串

我们需要编写一个包含两个字符串的JavaScript函数。我们称它们为str1和str2。然后,该函数应找出两个输入字符串共有的最长的连续字符串,并返回该公共字符串。

例如-

如果输入字符串是-

const str1 = 'ABABC';
const str2 = 'BABCA';

然后输出字符串应该是-

const output = 'BABC';

示例

以下是代码-

const str1 = 'ABABC';
const str2 = 'BABCA';
const findCommon = (str1 = '', str2 = '') => {
   const s1 = [...str1];
   const s2 = [...str2];
   const arr = Array(s2.length + 1).fill(null).map(() => {
      return Array(s1.length + 1).fill(null);
   });
   for (let j = 0; j <= s1.length; j += 1) {
      arr[0][j] = 0;
   }
   for (let i = 0; i <= s2.length; i += 1) {
      arr[i][0] = 0;
   }
   let len = 0;
   let col = 0;
   let row = 0;
   for (let i = 1; i <= s2.length; i += 1) {
      for (let j = 1; j <= s1.length; j += 1) {
         if (s1[j - 1] === s2[i - 1]) {
            arr[i][j] = arr[i - 1][j - 1] + 1;
         }
         else {
            arr[i][j] = 0;
         }
         if (arr[i][j] > len) {
            len = arr[i][j];
            col = j;
            row = i;
         }
      }
   }
   if (len === 0) {
      return '';
   }
   let res = '';
   while (arr[row][col] > 0) {
      res = s1[col - 1] + res;
      row -= 1;
      col -= 1;
   }
   return res;
};
console.log(findCommon(str1, str2));

输出结果

以下是控制台上的输出-

BABC