-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
42cc754
commit d08c45c
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
void lcs(string X, string Y, int m, int n) | ||
{ | ||
int L[m + 1][n + 1]; | ||
|
||
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 index = L[m][n]; | ||
char lcs[index + 1]; | ||
lcs[index] = '\0'; | ||
|
||
int i = m, j = n; | ||
while (i > 0 && j > 0) | ||
{ | ||
if (X[i - 1] == Y[j - 1]) | ||
{ | ||
lcs[index - 1] = X[i - 1]; | ||
i--, j--, index--; | ||
} | ||
else if (L[i - 1][j] > L[i][j - 1]) | ||
{ | ||
i--; | ||
} | ||
else | ||
{ | ||
j--; | ||
} | ||
} | ||
cout << lcs << endl; | ||
} | ||
int main() | ||
{ | ||
string X, Y; | ||
cin >> X >> Y; | ||
int m = X.length(); | ||
int n = Y.length(); | ||
lcs(X, Y, m, n); | ||
return 0; | ||
} | ||
|
||
/* | ||
Time Complexity : O(n^2) | ||
Space Complexity : O(n^2) | ||
The user is expected to enter the two string whose longest common | ||
subsequence is to be found. | ||
Input : AGGTAB | ||
GXTXAYB | ||
Output : GTAB |