题解 | #公共子串计算#

公共子串计算

https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

const readline = require('readline');

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

let s1 = ''
let s2 = ''
let row = 0

rl.on('line', function (line) {
    row++
    if(row === 1) {
        s1 = line
    }else if(row === 2) {
        s2 = line
        if(s1.length > s2.length)
            [s1, s2] = [s2, s1]
        // 使用双指针法
        let [left ,right] = [0, 1]
        let max = 0
        while(left < s1.length) {
            // 左指针移动,判断
            let tmp = s1.slice(left, right + 1)
            if(s2.includes(tmp)){
                max = Math.max(max, tmp.length)
            }
            // 右指针移动判断
            while(right < s1.length && s2.includes(tmp)){
                max = Math.max(max, tmp.length)
                right++
                tmp = s1.slice(left, right + 1)
            }
            left++
        }
        console.log(max)
    }
});

全部评论

相关推荐

JamesGosling1:同一个公司的实习为什么写三次,就算是不同的小组的话,直接写一段要好点吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务