题解 | 最长公共子串
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
#include <iterator> #include <string> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * longest common subsequence * @param s1 string字符串 the string * @param s2 string字符串 the string * @return string字符串 */ string LCS(string s1, string s2) { // write code here if (s1.empty() || s2.empty()) { return "-1"; } int n = s1.size(); int m = s2.size(); s1 = " " + s1; s2 = " " + s2; int maxlen = INT_MIN; int endindex = 0; 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 (s1[i] == s2[j]) { dp[i][j] = dp[i - 1][j - 1] + 1; if (dp[i][j] > maxlen) { maxlen = dp[i][j]; endindex = i; } } else { dp[i][j] = 0; } } } // 提取最长公共子串 string result = s1.substr(endindex - maxlen + 1, maxlen); return result; } };