LCS Dynamic Programming Table (Java)
Compute the longest common subsequence of two Java strings using dynamic programming with table reconstruction.
Code
public class LCS {
public static String longestCommonSubseq(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { if (a.charAt(i - 1) == b.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]); }
StringBuilder sb = new StringBuilder(); int i = m, j = n;
while (i > 0 && j > 0) { if (a.charAt(i - 1) == b.charAt(j - 1)) { sb.insert(0, a.charAt(i - 1)); i--; j--; } else if (dp[i - 1][j] > dp[i][j - 1]) i--; else j--; }
return sb.toString();
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.