forked from PhysicsX/ExampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.cpp
More file actions
61 lines (43 loc) · 1.42 KB
/
LongestCommonSubsequence.cpp
File metadata and controls
61 lines (43 loc) · 1.42 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
#include <bits/stdc++.h>
#include <vector>
//A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Longest common subsequence (LCS) of 2 sequences is a subsequence, with maximal length, which is common to both the sequences.
using namespace std;
using iter = string::const_iterator;
// global vector which is used for memorization
std::vector<std::vector<int>> vec;
int MaxChildRanges(iter b1, iter e1, iter b2, iter e2)
{
auto& mem = vec[e1-b1][e2-b2];
int result;
if(mem != -1)
result = mem;
else if(b1==e1 || b2==e2)
result = 0;
else if(*b1 == *b2)
result = 1 + MaxChildRanges(next(b1), e1, next(b2), e2);
else
result = max( MaxChildRanges(next(b1), e1, b2, e2),
MaxChildRanges(b1, e1, next(b2), e2));
return result;
}
int commonChild(const string& s1, const string& s2) {
// fill the vector
for(int i = 0; i < s1.size()+1; i++)
{
std::vector<int> tmp;
for(int j = 0; j < s2.size()+1; j++)
{
tmp.push_back(-1);
}
vec.push_back(tmp);
}
return MaxChildRanges(s1.begin(), s1.end(), s2.begin(), s2.end());
}
int main()
{
std::string str1 {"SHINCHAN"};
std::string str2 {"NOHARAAA"};
int result = commonChild(str1, str2);
cout << result << "\n";
return 0;
}