Problem :-
- Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
Example :-
- s1=Howard
- s2=Hogwartz
- s(Ans)=Howar
- |s|=5
Use Desktop Version Of This Site For Better View.
Idea :-
- LCS[m][n] stores the solution of first m chars of s1 and first n chars of s2(sub problem).
- LCS[m][n] = LCS[m-1][n-1] if s1[m]=s2[n]
= max(LCS[m-1][n] , LCS[m,n-1]) otherwise
where m is the no. of chars to be consider of s1(substring) and n is no. of chars to be consider of s2(substring).
Programme :-
#include<stdio.h>
char s1[20],s2[20];
int findmax(int x,int y)
{
return(x>y?x:y);
}
void findLcs(int i,int j,int lcs[strlen(s1)+1][strlen(s2)+1])
{
int flag;
if(i>0 && j>0)
{
if(lcs[i][j]>lcs[i-1][j-1])
{
j=j-1;
flag=1;
}
i--;
findLcs(i,j,lcs);
if(flag==1){
printf("%c ",s1[i]);
}
return;
}
}
main()
{
printf("ENTER THE FIRST STRING : ");
scanf("%s",s1);
printf("ENTER THE SECOND STRING : ");
scanf("%s",s2);
int lcs[strlen(s1)+1][strlen(s2)+1];
int i,j;
for(i=0;i<=strlen(s1);i++)
{
for(j=0;j<=strlen(s2);j++)
{
if(i==0 || j==0)
{
lcs[i][j]=0;
}
else if(s1[i-1]==s2[j-1])
{
lcs[i][j]=lcs[i-1][j-1]+1;
}
else
{
lcs[i][j]=findmax(lcs[i-1][j],lcs[i][j-1]);
}
printf("LCS[%d][%d] : %d \t",i,j,lcs[i][j]);
}
printf("\n");
}
i=strlen(s1);
j=strlen(s2);
printf("\nLARGEST COMMON SUBSEQUENCE : - ");
findLcs(i,j,lcs);
}
Comments
Post a Comment