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

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

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

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let [a, b, num] = [undefined, undefined, 0]

rl.on('line', function (line) {
    num++
    if(num === 1){
        a = line
    }else if(num === 2){
        b = line
    }
    if(num === 2) {
        console.log(getCommonStr(a,b))
    }
});


/**
 * @function 找到a、b字符串的公共子字串
 * @params 两个字符串
 * @return 两个字符串的公共子串
 */ 
function getCommonStr(a: string, b:string){
    // 1、得到较长长度的字符串
    const longStr = a.length > b.length? a : b
    const shortStr = a.length > b.length? b : a
    // 2、初始化公共字符串与临时字符串
    let [commmon, tmp] = ['','']
    // 3、循环遍历短字符串的各个字串,看是不是包含在长字符串中
    for(let i = 0; i < shortStr.length; i++){
        for(let j = shortStr.length - 1; j >= i; j--){
            // 4、如果包含在长字符串中,证明是公共子字符串
            if(longStr.indexOf(shortStr.slice(i, j+1)) !== -1){
                tmp =  shortStr.slice(i, j+1)
            }
            // 5、如果临时保存的公共字符串长度大于common的则重新赋值给common
            if(tmp.length > commmon.length){
                commmon = tmp
            }
        }
    }
    // 6、最后得到的就是最长的公共子字符串了
    return commmon
}

全部评论

相关推荐

我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务