-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcs.cpp
More file actions
67 lines (56 loc) · 1.5 KB
/
lcs.cpp
File metadata and controls
67 lines (56 loc) · 1.5 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
#include "lcs.hpp"
/* Returns LCS for comparetive and original patterns */
std::string longestCommonSubsequence(std::string X, std::string Y)
{
int m = X.size();
int n = Y.size();
std::vector< std::vector<int> > L( ( m+1 ), std::vector<int> ( n+1 ) );
/* Construct L[m+1][n+1] using Tabulation */
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
/* Fill L[m][0] and L[n][0] with zeros */
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] = std::max(L[i - 1][j], L[i][j - 1]);
}
}
}
/* Traceback the LCS from cell L[m][n] to cell L[0][0] */
int index = L[m][n];
/* Array to store the lcs string */
std::vector<char> lcs(index);
while ((m > 0) && (n > 0))
{
if (X[m - 1] == Y[n - 1])
{
/* Current char is part of LCS */
lcs[index - 1] = X[m - 1];
/* Decrement values of m, n and index */
m--;
n--;
index--;
}
/* Follow the direction of larger value */
else if (L[m - 1][n] > L[m][n - 1])
{
m--;
}
else
{
n--;
}
}
/* Copy char to string */
std::string retValue(lcs.begin(), lcs.end());
return retValue;
}