Method 1 - Using DP array to generate the subsequence#
Lets look at the dp array again, say for string text1 = abcde, text2 = ace and LCS = ace:
Ø
a
c
e
Ø
0
0
0
0
a
0
1
1
1
b
0
1
1
1
c
0
1
2
2
d
0
1
2
2
e
0
1
2
3
Now, lets look at it closely:
We begin traceback from the bottom-right corner, marking cells that contribute to the LCS and indicating diagonal movements (matching characters) for reconstruction.
public String longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp =newint[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]= 1 + dp[i - 1][j - 1];
} else {
dp[i][j]= Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// No return in the loop, calculate LCS length firstint idx = dp[m][n];
// Handle the case where there's no LCS (idx = 0)if (idx == 0) {
return"";
}
char[] lcs =newchar[idx];
int i = m;
int j = n;
while (i > 0 && j > 0) {
// If current character in text1 and text2 are same,// then current character is part of LCSif (text1.charAt(i - 1) == text2.charAt(j - 1)) {
// Put current character in result lcs[idx - 1]= text1.charAt(i - 1);
i--;
j--;
idx--;
}
// If not same, then find the larger of two and// go in the direction of larger valueelseif (dp[i - 1][j]> dp[i][j - 1]) {
i--;
}
else {
j--;
}
}
returnnew String(lcs);
}