-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Common_Sequence(LCS).cpp
More file actions
109 lines (99 loc) ยท 1.57 KB
/
Longest_Common_Sequence(LCS).cpp
File metadata and controls
109 lines (99 loc) ยท 1.57 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<iostream>
#include<string.h>
using namespace std;
// Longest common sequence
int m, n;
class LCS{
private:
char x[20],y[20];
public:
void LCS_main();
void LCS_length();
void print_LCS(char b[20][20],char x[20],int i,int j);
};
void LCS::LCS_main()
{
cout<<"\nEnter the string X : ";
cin>>x;
cout<<"\nEnter the string Y : ";
cin>>y;
LCS_length();
}
void LCS::LCS_length()
{
m = strlen(x);
n = strlen(y);
for(int i=m-1;i>=0;i--)
{
x[i+1] = x[i];
}
for(int i=n-1;i>=0;i--)
{
y[i+1] = y[i];
}
char b[20][20];
int c[20][20];
for(int i=0;i<=m;i++)
{
c[i][0]=0;
}
for(int j=0;j<=n;j++)
{
c[0][j]=0;
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(x[i]==y[j])
{
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = 'D';
}
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';
}
}
}
cout<<"\nThe length of Longest Common Subsequence is : "<<c[m][n];;
cout<<"\nThe Longest Common Subsequence is : ";
print_LCS(b,x,m,n);
}
void LCS::print_LCS(char b[20][20],char x[20],int i,int j)
{
if (i==0 || j==0)
return;
if(b[i][j]=='D')
{
print_LCS(b,x,i-1,j-1);
cout<<x[i];
}
else if(b[i][j]=='U')
{
print_LCS(b,x,i-1,j);
}
else
{
print_LCS(b,x,i,j-1);
}
}
int main()
{
LCS l;
l.LCS_main();
}
/*OUTPUT
C:\Users\Admin\Downloads\DAA Codes>g++ LCS.cpp
C:\Users\Admin\Downloads\DAA Codes>a
Enter the string X : aggtab
Enter the string Y : gxtxayb
The length of Longest Common Subsequence is : 4
The Longest Common Subsequence is : gtab
*/