给定两个字符串X,Y,求二者最长的公共连续子串,如 X = [abcdefg],Y = [bacdegf],二者的最长公共连续子串是 cde 长度为3,
这里讨论 DP 方案。
考虑 m = X.length,n = Y.length 开辟一个大小为 m x n 的数组 d[m][n],使用 d[i][j] 表示以 X[i] 与 Y[j] 结尾的最长公共子串的长度,因为要求子串连续,所以对于 X[i] 与 Y[j],它们要么与之前的公共子串构成新的公共子串,要么就是不构成公共子串,故状态转移方程为
- 1.If X[i] == Y[j], then dp[i][j] = dp[i-1][j-1] + 1
- 2. If X[i] != Y[j], then dp[i][j] = 0
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define INF (~(1<<31))
int main(){
string s1, s2;
cin >> s1 >> s2;
vector<vector<int>> mat(s1.size(), vector<int>(s2.size(), 0));
int pos = 0, maxLen = -INF;
for(size_t i = 0; i < s1.size(); ++i){
for(size_t j = 0; j < s2.size(); ++j){
if(s1[i] == s2[j]){
if(i == 0 || j == 0){
mat[i][j] = 1;
}else{
mat[i][j] = mat[i-1][j-1] + 1;
}
}
if(maxLen < mat[i][j]){
maxLen = mat[i][j];
pos = i+1-maxLen;
}
}
}
cout << s1.substr(pos, maxLen);
return 0;
}