【中等】算法nodeJs:查找两个字符串a,b中的最长公共子串

85 阅读1分钟

描述

对于给定的两个字符串 s 和 t,你需要找出它们的最长公共子串。特别地,如果存在多个答案,输出在较短串中最先出现的那个。

子串为从原字符串中,连续的选择一段字符(可以全选、可以不选)得到的新字符串。
如果字符串 a 的一个子串 a′ 与字符串 b 的一个子串 b′ 完全相等,那么子串 a′,b′ 是字符串 a,b 的一个公共子串。

输入描述:

第一行输入一个长度为 1≦len(s)≦300、仅由小写字母组成的字符串 s。
第二行输入一个长度为 1≦len(t)≦300、仅由小写字母组成的字符串 t。

输出描述:

输出一个字符串,代表 s 和 t 的最长公共子串。如果存在多个答案,输出在较短串中最先出现的那个。

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    let s = await readline();
    let t = await readline();
    const longStr = s.length > t.length ? s : t;
    const shortStr = s.length < t.length ? s : t;
    let maxStr = "";
    for (let i = 0; i < shortStr.length; i++) {
        for (let j = i + 1; j < shortStr.length; j++) {
            let sliceStr = shortStr.slice(i, j + 1);
            if (longStr.indexOf(sliceStr) !== -1)
                maxStr = sliceStr.length > maxStr.length ? sliceStr : maxStr;
        }
    }
    console.log(maxStr);
})();