题解 | #查找两个字符串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
}

全部评论

相关推荐

榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
点赞 评论 收藏
分享
吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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