题解 | #最长公共子串#

最长公共子串

https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * longest common substring
 * @param str1 string字符串 the string
 * @param str2 string字符串 the string
 * @return string字符串
 */
function LCS(str1, str2) {
    // write code here
    if (str1.length == 0 || str2.length == 0) return -1;
    // 动态规划的状态转移方程:
    // if(str1[i]==str2[j]){dp[i-1][j-1]+str1[i]}

    // 吸取前面的经验,给把i=0和j=0的地方全部置为空字符串
    str1 = "_" + str1;
    str2 = "_" + str2;
    let maxL = 0;
    let maxP = [0, 0];
    let dp = [];
    for (let i = 0; i < str1.length + 1; i++) {
        if (i == 0) {
            dp.push(new Array(str2.length).fill(""));
            continue;
        }
        dp.push([]);
        for (let j = 0; j < str2.length; j++) {
            if (j == 0) {
                dp[i].push("");
                continue;
            }
            if (i == 10 && j == 8) {
                console.log(dp[i][j]);
                console.log(dp[i][j]);
            }
            if (str1[i] == str2[j]) {
                dp[i].push(dp[i - 1][j - 1] + str1[i]);
                // console.log(dp)
                if (!(maxL > dp[i][j].length)) {
                    maxL = dp[i][j].length;
                    maxP = [i, j];
                }
            } else {
                dp[i].push("");
            }
        }
    }

    return dp[maxP[0]][maxP[1]];
}
module.exports = {
    LCS: LCS,
};

全部评论

相关推荐

点赞 评论 收藏
分享
来个厂收我吧:首先,市场侧求职我不是很懂。 但是,如果hr把这份简历给我,我会觉得求职人不适合做产品经理。 问题点: 1,简历的字体格式不统一,排版不尽如人意 2,重点不突出,建议参考star法则写个人经历 3,印尼官方货币名称为印度尼西亚卢比(IDR),且GMV690000印尼盾换算为305人民币,总成交额不高。 4,右上角的意向职位在发给其他公司时记得删除。 5,你所有的经历都是新媒体运营,但是你要投市场营销岗位,jd和简历不匹配,建议用AI+提示词,参照多个jd改一下经历内容。 修改建议: 1,统一字体(中文:思源黑体或微软雅黑,英文数字:time new romans),在word中通过表格进行排版(b站学) 2,校招个人经历权重:实习经历=创业经历(大创另算)>项目经历>实训经历>校园经历 3,请将项目经历时间顺序改为倒序,最新的放最上方。 4,求职方向不同,简历文字描述侧重点也需要不同。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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