题解 | #最长公共子串#
最长公共子串
http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
public:
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
string LCS(string str1, string str2) {
vector<vector<int>> dp(str1.size()+1, vector<int>(str2.size()+1, 0));
int maxlength = 0;
int maxlastindex = 0;
for (int i=1; i<=str1.size(); i++){
for (int j=1; j<=str2.size(); 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] > maxlength){
maxlength = dp[i][j];
maxlastindex = i - 1;
}
}
}
}
return str1.substr(maxlastindex - maxlength + 1, maxlength);
// write code here
}
};