-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathLCS.cpp
More file actions
64 lines (58 loc) · 1.54 KB
/
LCS.cpp
File metadata and controls
64 lines (58 loc) · 1.54 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
#include <iostream>
#include <string>
#include <vector>
std::string longestCommonSubsequence(const std::string s1, std::string s2)
{
int n = s1.size();
int m = s2.size();
std::vector<std::vector<int>> dp(n+1, std::vector<int>(n+1, 0));
for(int i=1; i<n; ++i)
{
for(int j=1; j<m; ++j)
{
if(s1[i-1] == s2[i-2])
{
dp[i][j] = dp[i][j] + 1;
}
else
{
dp[i][j] = std::max(dp[i-1][j], dp[i][j-1]);
}
}
}
int i = n, j=m;
std::string lcs;
/*
After creating dp table it is possible to find max sub array.
Start from the right bottom and check the string members if members
are same then go to previous diagonal position if not then check the numbers
top and left positions if top is greater than left move --i else --j.
Because if one positon is greater than other that means there is a match for
current character. If there is same char there will be increment.
*/
while(i>0 && j>0)
{
if(s1[i-1] == s2[j-1])
{
lcs = s1[i-1] + lcs;
--i; --j;
}
else if(dp[i-1][j] > dp[i][j-1])
{
--i;
}
else
{
--j;
}
}
return lcs;
}
int main()
{
std::string s1 = "ABCBDAB";
std::string s2 = "BDCABA";
std::string lcs = longestCommonSubsequence(s1, s2);
std::cout << "Longest common subsequence: " << lcs << std::endl; // Output: "BCBA"
return 0;
}