-
Notifications
You must be signed in to change notification settings - Fork 0
/
LCS.c
73 lines (68 loc) · 1.23 KB
/
LCS.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include<string.h>
int max(int a, int b)
{
if(a>b){
return a;
}
return b;
}
void lcs(char x[], char y[])
{
int m=strlen(x);
int n=strlen(y);
int L[20][20];
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
if(i==0 || j==0){
L[i][j]=0;
}
else if(x[i-1]==y[j-1])
{
L[i][j]=L[i-1][j-1]+1;
}
else
{
L[i][j]=max(L[i-1][j],L[i][j-1]);
}
}
}
int ind=L[m][n];
char str[20];
int i=m;
int j=n;
while(i>0 && j>0){
if(x[i-1]==y[j-1])
{
str[ind-1]=x[i-1];
i--;
j--;
ind--;
}
else if(L[i-1][j]>L[i][j-1])
{
i--;
}
else{
j--;
}
}
printf("The longest common subsequence: %s",str);
}
int main()
{
char x[20],y[20];
scanf("%s",x);
scanf("%s",y);
lcs(x,y);
return 0;
}
/*
input:
aggtab
gxtxayab
output:
The longest common subsequence: gtab
*/