Print Longest Common Subsequence

This program prints the longest common subsequence between two strings.

Problem Statement

Write a Java program to print longest common subsequence of "Eduinq" and "Enquiry".

Source Code

1 public class PrintLCS {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Print LCS");
4 String s1="Eduinq", s2="Enquiry";
5 int m=s1.length(), n=s2.length();
6 int[][] dp=new int[m+1][n+1];
7 for(int i=1;i<=m;i++){
8 for(int j=1;j<=n;j++){
9 if(s1.charAt(i-1)==s2.charAt(j-1))
10 dp[i][j]=1+dp[i-1][j-1];
11 else dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
12 }
13 }
14 int i=m, j=n;
15 StringBuilder lcs=new StringBuilder();
16 while(i>0 && j>0){
17 if(s1.charAt(i-1)==s2.charAt(j-1)){
18 lcs.insert(0,s1.charAt(i-1));
19 i--; j--;
20 } else if(dp[i-1][j]>dp[i][j-1]) i--;
21 else j--;
22 }
23 System.out.println("Longest common subsequence: "+lcs.toString());
24 }
25 }

Program Output

Eduinq Print LCS
Longest common subsequence: Enq

Explanation

DP table stores subsequence lengths. - Backtracking reconstructs subsequence. - Together prints longest common subsequence. Conclusion: Shows how to print longest common subsequence using DP.

Quick Links to Explore