最长公共子序列大小(子序列不用连着)
public int longestCommonSubsequence(String text1, String text2) {
int n1 = text1.length(), n2 = text2.length();
int[][] dp = new int[n1 + 1][n2 + 1];
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n2; j++) {
char c1 = text1.charAt(i - 1);
char c2 = text2.charAt(j - 1);
// 相等情况
if (c1 == c2) dp[i][j] = dp[i - 1][j - 1] + 1;
// 不等情况
else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
return dp[n1][n2];
}
最长公共子序列输出
public int longestCommonSubsequence(String text1, String text2) {
// 同上面的模版
/* ------- print ------- */
int i = n1, j = n2;
StringBuffer sb = new StringBuffer();
while (i > 0 && j > 0) {
char c1 = text1.charAt(i - 1);
char c2 = text2.charAt(j - 1);
if (c1 == c2) {
sb.append(c1);
// 向左上角遍历
i--; j--;
} else {
// 向上
if (dp[i - 1][j] > dp[i][j - 1]) i--;
// 向左
else j--;
}
}
System.out.println(sb.reverse());
/* ------- end ------- */
return dp[n1][n2];
}