题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

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

    while(line = await readline()){

        // 首先得找出 两个字符串中, 最大和最小的分别是哪个?

        // 记录 2个 变量,一个是 最长 长度 l, 一个 公共子串res

        // 找到后 先从最小的 那个开始遍历, 以 i -> short.length

        // 然后再  遍历, 以 j = i -> short.length

        // 在 short 里 截取字符串 i --> j+1

        // 如果 最长的里面找到了 截取的串, 并且 串的长度 > 最长长度 l, 把最长子串更新为截取的值, 把最长长度更新为 截取串的长度

        // 输入结果 res

        const line1 = line;

        const line2 = await readline();

        let short = line1.length < line2.length ? line1 : line2;

        let long = line1.length < line2.length ? line2 : line1;

        let len = 0;

        let res = '';

        for (let i = 0i < short.lengthi++){

            for (let j = ij < short.lengthj++) {

                let str = short.substring(ij+1);

                if (long.includes(str)) {

                    if (str.length > len) {

                        res = str;

                        len = res.length;

                    }

                }

            }

        }

        console.log(res);

    }

}()

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务