题解 | 最长公共子串

最长公共子串

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
    const n = str1.length
    const m = str2.length
    let maxLen = 0
    let endIndex = 0
    const dp = Array.from({length:n + 1}, () => Array( m + 1).fill(0))
    for (let i = 1; i<=n; i++) {
        for (let j = 1; j<=m; j++) {
            if (str1.charAt(i-1) === str2.charAt(j-1)) {
                dp[i][j] = dp[i-1][j-1] + 1
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j]
                    endIndex = i
                }
            }
            else {
                dp[i][j] = 0
            }
        }
    }
    return str1.slice(endIndex-maxLen, endIndex)
}
module.exports = {
    LCS : LCS
};

全部评论

相关推荐

03-31 18:02
门头沟学院 Java
白日梦想家_等打包版:不要的哦佛给我
点赞 评论 收藏
分享
高斯林的信徒:武大简历挂?我勒个骚岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务