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();
}
}How the snippet works
LCS Dynamic Programming Table (Java) keeps everything in the class LCS and the function longestCommonSubseq.
The file repeats itself only inside for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { if (a.charAt(i - 1) == b.charAt(j - 1….
Applying it
The primary signature is public static String longestCommonSubseq(String a, String b)
Statements that matter
return sb.toString();
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `longestCommonSubseq` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.