题解 | #最长公共子序列(二)#

最长公共子序列(二)

https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11

package main

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * longest common subsequence
 * @param str1 string字符串 the string
 * @param str2 string字符串 the string
 * @return string字符串
*/
func LCS( str1 string ,  str2 string ) string {
    // write code here
    m, n := len(str1), len(str2)
    // dp[i][j] 表示str1的前i个字符与str2的前j个字符的最长公共子序列的长度 
    dp := make([][]int, m+1)
    for i := range dp {
        dp[i] = make([]int, n+1)
    }

    // 填充dp数组
    for i := 1; i <= m; i++ {
        for j := 1; j <= n; j++ {
            if str1[i-1] == str2[j-1] {
                dp[i][j] = dp[i-1][j-1] + 1
            } else {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
            }
        }
    }

    // 构建LCS
    lcs := []rune{}
    i, j := m, n
    for i > 0 && j > 0 {
        if str1[i-1] == str2[j-1] {
            lcs = append([]rune{rune(str1[i-1])}, lcs...)
            i--
            j--
        } else if dp[i-1][j] > dp[i][j-1] {
            // 表示当前st1的i-1位置,相较于str2的j位置的LCS长度更长,应该向左移动,否则相反
            i--
        } else {
            j--
        }
    }

    if len(lcs) == 0 {
        return "-1"
    }
    return string(lcs)
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务