class Solution {
public:
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
/*
dp(i,j)表示以i,j结尾的最大子串长度,最长公共子串,
不断刷新最大值。
startIndex,len
*/
string LCS(string str1, string str2) {
int len1 = str1.size(), len2 = str2.size();
if (len1 == 0 || len2 == 0) {
return "";
}
vector<vector<int>>dp(len1 + 1, vector<int>(len2 + 1, 0));
int startIndex = 0, maxLen = 0;
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
}
if (maxLen < dp[i][j]) {
maxLen = dp[i][j];
startIndex = i - dp[i][j];
}
}
}
return str1.substr(startIndex, maxLen);
}
};