2023-2-17 BM66最長公共子串
2023-2-17 BM66最長公共子串 #include <vector>
class Solution {
public:
/**
* longest common substring
* @param str1 string字元串 the string
* @param str2 string字元串 the string
* @return string字元串
*/
string LCS(string str1, string str2) {
// write code here
int m = str1.size();
int n = str2.size();
vector<vector<int> > dp(m+1, vector<int>(n+1, 0));
int maxLen = 0;
int endIdx = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (str1[i-1] != str2[j-1]) {
dp[i][j] = 0;
} else {
dp[i][j] = dp[i-1][j-1] + 1;
}
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endIdx = i;
}
}
}
return str1.substr(endIdx - maxLen, maxLen);
}
};