Skip to content

Commit d08c45c

Browse files
Create lcs.cpp
1 parent 42cc754 commit d08c45c

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

lcs.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
void lcs(string X, string Y, int m, int n)
4+
{
5+
int L[m + 1][n + 1];
6+
7+
for (int i = 0; i <= m; i++)
8+
{
9+
for (int j = 0; j <= n; j++)
10+
{
11+
if (i == 0 || j == 0)
12+
{
13+
L[i][j] = 0;
14+
}
15+
else if (X[i - 1] == Y[j - 1])
16+
{
17+
L[i][j] = L[i - 1][j - 1] + 1;
18+
}
19+
else
20+
{
21+
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
22+
}
23+
}
24+
}
25+
26+
int index = L[m][n];
27+
char lcs[index + 1];
28+
lcs[index] = '\0';
29+
30+
int i = m, j = n;
31+
while (i > 0 && j > 0)
32+
{
33+
if (X[i - 1] == Y[j - 1])
34+
{
35+
lcs[index - 1] = X[i - 1];
36+
i--, j--, index--;
37+
}
38+
else if (L[i - 1][j] > L[i][j - 1])
39+
{
40+
i--;
41+
}
42+
else
43+
{
44+
j--;
45+
}
46+
}
47+
cout << lcs << endl;
48+
}
49+
int main()
50+
{
51+
string X, Y;
52+
cin >> X >> Y;
53+
int m = X.length();
54+
int n = Y.length();
55+
lcs(X, Y, m, n);
56+
return 0;
57+
}
58+
59+
/*
60+
Time Complexity : O(n^2)
61+
Space Complexity : O(n^2)
62+
The user is expected to enter the two string whose longest common
63+
subsequence is to be found.
64+
Input : AGGTAB
65+
GXTXAYB
66+
Output : GTAB

0 commit comments

Comments
 (0)