class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int M = text1.length();
int N = text2.length();
int[][] dp = new int[M + 1][N + 1];
for (int i = 1; i <= M; ++i) {
for (int j = 1; j <= N; ++j) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[M][N];
}
}
作者:fuxuemingzhu
链接:https://leetcode.cn/problems/longest-common-subsequence/solution/fu-xue-ming-zhu-er-wei-dong-tai-gui-hua-r5ez6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Q: 为什么转移方程是代码A,而不是代码B
Part A:
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
Part B:
int max = Math.max(Math.max(dp[i - 1][j - 1], dp[i - 1][j]), dp[i][j - 1]);
if (c1 == c2) {
dp[i][j] = max + 1;
} else {
dp[i][j] = max;
}
解释1:
解释2:
可以注意到下方的第四行第四列的3,如果使用part B代码, 则bsb和efb的最长公共子序列的长度是2,而正确的是1,这是因为字符串中存在重复字符