-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpylcs.cpp
86 lines (77 loc) · 2.08 KB
/
pylcs.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// modified from
// https://github.com/Meteorix/pylcs
#include <string>
#include <vector>
#include <algorithm>
#include "pylcs.hpp"
#include "utf8_unicode.hpp"
using std::string;
using std::vector;
// 最长公共子序列(不连续)
int lcs_length_(const string &str1, const string &str2) {
if (str1 == "" || str2 == "")
return 0;
vector<string> s1 = utf8_split(str1);
vector<string> s2 = utf8_split(str2);
int m = s1.size();
int n = s2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
int i, j;
// printf("%d %d\n", m, n);
for (i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for (j = 0; j <= n; j++) {
dp[0][j] = 0;
}
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
if (dp[i - 1][j] >= dp[i][j - 1])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i][j-1];
}
}
}
return dp[m][n];
}
// 最长公共子串(连续)
// modified by Lorenz Schiffmann, July 2021
// modified to return a struct including also the start position of the lcstr
structRet lcs2_length_(const string &str1, const string &str2) {
structRet ret;
ret.max = 0;
ret.start = 0;
if (str1 == "" || str2 == "")
return ret;
vector<string> s1 = utf8_split(str1);
vector<string> s2 = utf8_split(str2);
int m = s1.size();
int n = s2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
int i, j;
for (i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for (j = 0; j <= n; j++) {
dp[0][j] = 0;
}
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > ret.max){
ret.max = dp[i][j];
ret.start = i-ret.max;
}
}
else {
dp[i][j] = 0;
}
}
}
return ret;
}