1143.最长公共子序列
1143.最长公共子序列
题解
LCS
//state: dp[i][j]表示test1的前i个字符和test2的前j的字串的最长公共子序列
//function: dp[i][j]=dp[i-1][j-1]+1或者=dp[i-1][j]或者=dp[i][j-1]
//intialize:dp[0][0]=0
//answer: dp[len(text1)][len(text1)]
代码
package main func longestCommonSubsequence(text1 string, text2 string) int { dp := make([][]int, len(text1)+1) for idx := range dp { dp[idx] = make([]int, len(text2)+1) } for i := 1; i <= len(text1); i++ { for j := 1; j <= len(text2); j++ { if text1[i-1] == text2[j-1] { dp[i][j] = dp[i-1][j-1] + 1 } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]) } } } return dp[len(text1)][len(text2)] } func max(a, b int) int { if a > b { return a } return b }