Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code to find longest common subsequence #389

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Dynamic Programming/longestcommonsubsequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import java.io.*;
import java.util.*;

public class longestcommonsubsequence
{
public static int find(char[] arr,char[] brr,int n,int m)
{
int[][] dp = new int[n+1][m+1];
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i == 0 || j == 0)
dp[i][j] = 0;
else if(arr[i-1] == brr[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]);
}
}
return dp[n][m];
}
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String str1 = br.readLine();
char[] arr = str.toCharArray();
char[] brr = str1.toCharArray();
int n = str.length();
int m = str1.length();
System.out.println("Length of the maximum common subsequence : " + find(arr,brr,n,m));
}
}