最大公共子序列
int MatchTopic::LongestCommonSequence(const std::string &topic, const std::string &test)
{
int lengthOfTopic = topic.size();
int lengthOfTest = test.size();
std::vector<std::vector<int>> c(lengthOfTopic + 1, std::vector<int>(lengthOfTest + 1, 0));
for (int i = 0; i <= lengthOfTopic; i++) {
for (int j = 0; j <= lengthOfTest; j++) {
if (i == 0 || j == 0) {
c[i][j] = 0;
}
else if (topic[i - 1] == test[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
}
else if (c[i - 1][j] >= c[i][j - 1]) {
c[i][j] = c[i - 1][j];
}
else {
c[i][j] = c[i][j - 1];
}
}
}
return c[lengthOfTopic][lengthOfTest];
}
最大公共子串
int MatchTopic::LongestCommonSubstring(const std::string &topic, const std::string &test)
{
int lengthOfTopic = topic.size();
int lengthOfTest = test.size();
int result = 0; //记录最长公共子串长度
std::vector<std::vector<int>> c(lengthOfTopic + 1, std::vector<int>(lengthOfTest + 1, 0));
for (int i = 0; i <= lengthOfTopic; i++) {
for (int j = 0; j <= lengthOfTest; j++) {
if (i == 0 || j == 0) {
c[i][j] = 0;
}
else if (topic[i - 1] == test[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
if (c[i][j] > result) {
result = c[i][j];
}
}
else {
c[i][j] = 0;
}
}
}
return result;
}