题解 | #公共子串计算# 暴力和动态规划

公共子串计算

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

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

// 方法一:暴力法
void async function () {
    const str1 = await readline();
    const str2 = await readline();
    const [longStr,shortStr] = str1.length > str2.length?[str1,str2]:[str2,str1];
    let res = 0;
    for(let i = 0; i < shortStr.length; i++){
        for(let j = i+res; j < shortStr.length; j++){
            if(longStr.indexOf(shortStr.slice(i,j+1))!=-1) res = j-i+1;
        }
    }
    console.log(res);
}()

// 方法二:动态规划
void async function () {
    const str1 = await readline();
    const str2 = await readline();
    const dp = Array.from(Array(str1.length+1),()=>Array(str2.length+1).fill(0));
    let max = 0;
    for(let i = 0; i < str1.length; i++){
        for(let j = 0; j < str2.length; j++){
            dp[i+1][j+1] = str1[i] == str2[j]? dp[i][j]+1:0;
            max = Math.max(dp[i+1][j+1],max);
        }
    }
    // console.log(dp)
    console.log(max)
}()

全部评论

相关推荐

评论
2
1
分享

创作者周榜

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