【牛客题霸每日一题】NC127 最长公共子串 C++ 题解
简单DP,tag[i][j] 表示截止到 s1 的 i 位置和 s2 的 j 位置的最长公共子串长度。由于子串连续,最后找到最大值位置向前递推即可。代码如下:
class Solution {
public:
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
string LCS(string s1, string s2) {
// write code here
int m = s1.size();
int n = s2.size();
int len = 0;
string ret = "";
int x, y;
vector<vector<int>>tag(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (s1[i - 1] == s2[j - 1]) {
tag[i][j] = tag[i - 1][j - 1] + 1;
if (len < tag[i][j]) {
len = tag[i][j];
x = i, y = j;
}
}
else
tag[i][j] = 0;
}
}
if (len == 0)ret = "-1";
else {
for (int i = len; i >= 1; --i) {
ret += s1[x - i];
}
}
return ret;
}
};


