Skip to content
This repository was archived by the owner on Oct 7, 2019. It is now read-only.

Commit

Permalink
Implemented longest common subsequence in C
Browse files Browse the repository at this point in the history
  • Loading branch information
rajashree23 committed Oct 7, 2018
1 parent 9062c49 commit 83dc758
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Binary file not shown.
63 changes: 63 additions & 0 deletions dynamic_programing/longest_common_subsequence/C/long_comm_subs.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include<stdio.h>
#include<string.h>

int i,j,m,n,c[20][20];
char x[20],y[20],b[20][20];

void print(int i,int j)
{
if(i==0 || j==0)
return;
if(b[i][j]=='c')
{
print(i-1,j-1);
printf("%c",x[i-1]);
}
else if(b[i][j]=='u')
print(i-1,j);
else
print(i,j-1);
}

void lcs()
{
m=strlen(x);
n=strlen(y);
for(i=0;i<=m;i++)
c[i][0]=0;
for(i=0;i<=n;i++)
c[0][i]=0;

//c, u and l denotes cross, upward and downward directions respectively
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
{
if(x[i-1]==y[j-1])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]='c';
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]='u';
}
else
{
c[i][j]=c[i][j-1];
b[i][j]='l';
}
}
}

int main()
{
printf("Enter 1st sequence:");
scanf("%s",x);
printf("Enter 2nd sequence:");
scanf("%s",y);
printf("\nThe Longest Common Subsequence is ");
lcs();
print(m,n);
return 0;
}

0 comments on commit 83dc758

Please sign in to comment.