题解 | #最长公共子串#
最长公共子串
http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
动态规划求解
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 maxLenth = 0; //记录最长公共子串的长度 int maxLastIndex = 0; //记录最长公共子串最后一个元素在字符串str1中的位置 int n = str1.size(), m = str2.size(); vector<vector<int> > dp(n+1, vector<int>(m+1, 0)); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (str1[i-1] == str2[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; //递推公式,两个字符相等的情况 if (dp[i][j] > maxLenth) { maxLenth = dp[i][j]; maxLastIndex = i-1; } } } } // 用法:substr(begin_index, length); return str1.substr(maxLastIndex - maxLenth + 1, maxLenth); } };