题解 | #最长公共子串#

最长公共子串

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

package main

// import "fmt"

/**
 * longest common substring
 * @param str1 string字符串 the string
 * @param str2 string字符串 the string
 * @return string字符串
 */
func LCS( str1 string ,  str2 string ) string {
    // write code here
    n := len(str1)
    m := len(str2)
    if n == 0 || m == 0 {
        return ""
    }
    dp := make([][]int, n+1)
    for i:=0;i<n+1;i++{
        dp[i] = make([]int, m+1)
        
    }
    maxlen := 0
    maxidx := 0
    for i:=1;i<=n;i++{
        for j:=1;j<=m;j++{
            if str1[i-1] == str2[j-1] {
                dp[i][j] = dp[i-1][j-1] + 1
                if dp[i][j] > maxlen {
                    maxlen = dp[i][j]
                    maxidx = i-1
                    
                }
            }else{
                dp[i][j] = 0
                
            }
            
        }
    }
    // fmt.Println(maxidx, maxlen)
    // return ""
    return str1[maxidx-maxlen+1:maxidx+1]
}

全部评论

相关推荐

03-31 18:02
门头沟学院 Java
白日梦想家_等打包版:不要的哦佛给我
点赞 评论 收藏
分享
海螺很能干:每次看到这种简历都没工作我就觉得离谱
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务