This Java program finds the longest common subsequence (LCS) between two input strings using dynamic programming. The LCS is the longest subsequence that appears in both strings in the same relative order.
Java Program
public class LongestCommonSubsequence {
// Function to find the length of the longest common subsequence
public static int findLCS(String str1, String str2) {
int m = str1.length();
int n = str2.length();
// Create a DP table to store the lengths of LCS for substrings
int[][] dp = new int[m + 1][n + 1];
// Build the dp table in a bottom-up manner
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0; // Base case: empty strings
} else if (str1.charAt(i – 1) == str2.charAt(j – 1)) {
dp[i][j] = dp[i – 1][j – 1] + 1; // Characters match
} else {
dp[i][j] = Math.max(dp[i – 1][j], dp[i][j – 1]); // Characters don’t match
}
}
}
// The length of the longest common subsequence is stored in dp[m][n]
return dp[m][n];
}
// Function to print the actual LCS by backtracking through the DP table
public static String getLCS(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m + 1][n + 1];
// Fill the dp table
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (str1.charAt(i – 1) == str2.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]); } } } // Backtrack to find the LCS StringBuilder lcs = new StringBuilder(); int i = m, j = n; while (i > 0 && j > 0) {
if (str1.charAt(i – 1) == str2.charAt(j – 1)) {
lcs.append(str1.charAt(i – 1)); // Character is part of the LCS
i–;
j–;
} else if (dp[i – 1][j] > dp[i][j – 1]) {
i–; // Move up
} else {
j–; // Move left
}
}
// Since we built the LCS in reverse, reverse it before returning
return lcs.reverse().toString();
}
public static void main(String[] args) {
String str1 = “ABCBDAB”;
String str2 = “BDCAB”;
// Find and print the length of the LCS
int lcsLength = findLCS(str1, str2);
System.out.println(“Length of the Longest Common Subsequence is: ” + lcsLength);
// Find and print the actual LCS
String lcs = getLCS(str1, str2);
System.out.println(“Longest Common Subsequence is: ” + lcs);
}
}
Explanation of the Program Structure
This program finds the longest common subsequence (LCS) between two input strings using dynamic programming. The LCS is defined as the longest subsequence that appears in both strings in the same relative order but not necessarily contiguously.
- findLCS function: This function computes the length of the longest common subsequence between two strings. It uses a dynamic programming table
dp[i][j]
where each entry represents the length of the LCS for substrings ofstr1
andstr2
ending at indicesi-1
andj-1
, respectively. The function fills this table in a bottom-up manner by checking if characters match and updating the table accordingly. - getLCS function: This function reconstructs the actual LCS from the dynamic programming table by backtracking through the table. Starting from the bottom-right corner of the table, it moves diagonally when characters match and chooses the direction (up or left) that maintains the longest subsequence when characters don’t match. The result is built in reverse and reversed before returning.
- main function: This function initializes two strings and calls both the
findLCS
andgetLCS
functions to print the length of the LCS and the actual LCS itself.
Step-by-Step Process:
- We initialize a dynamic programming table
dp
of size(m+1) x (n+1)
, wherem
andn
are the lengths of the two input strings. - We iterate through each character of both strings. If characters match, we set
dp[i][j] = dp[i-1][j-1] + 1
. If they don’t match, we take the maximum of the values from the previous row and column. - Once the table is filled, the value at
dp[m][n]
contains the length of the longest common subsequence. - To find the actual LCS, we backtrack through the table. We append characters to the result when they match and move accordingly when they don’t.
Example:
Consider the two strings:
str1 = "ABCBDAB"
str2 = "BDCAB"
The longest common subsequence between these strings is "BCAB"
, and its length is 4. The program will output:
Length of the Longest Common Subsequence is: 4
Longest Common Subsequence is: BCAB
Conclusion:
This Java program efficiently solves the problem of finding the longest common subsequence between two strings using dynamic programming. The time complexity of this solution is O(m * n)
, where m
and n
are the lengths of the two input strings. This makes it suitable for moderate-sized inputs and ensures optimal performance when comparing two sequences.