-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23 Printing Longest common subsequence
70 lines (50 loc) · 1.32 KB
/
23 Printing Longest common subsequence
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
23. Printing Longest common subsequence
https://youtu.be/x5hQvnUcjiM
Article Link of GFG : https://www.geeksforgeeks.org/printing-longest-common-subsequence/
--------------------------xxxxxxxxxxxxxxx---------------xxxxxxxxxxxxx CODE xxxxxxxxxxxxxxx-----------------------xxxxxxxxxxxxxxxxxxx------
#include <bits/stdc++.h>
using namespace std;
string LCS(string s1, string s2, int n, int m) {
string ans = "";
int dp[n + 1][m + 1]; // DP - matrix
// initialising the table
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++)
if (i == 0 || j == 0)
dp[i][j] = 0;
// filling the table
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
//if characters are matching
if (s1[i - 1] == s2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
// if characters aren't matching
else
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
int i = n, j = m;
while (i > 0 && j > 0) {
if (s1[i - 1] == s2[j - 1]) {
ans += s1[i - 1];
i--, j--;
}
else {
if (dp[i][j - 1] > dp[i - 1][j])
j--;
else
i--;
}
}
reverse(ans.begin(), ans.end());
return ans;
}
signed main() {
string s1, s2;
cin >> s1 >> s2;
int n = s1.length(), m = s2.length();
cout << LCS(s1, s2, n, m) << endl;
return 0;
}