题解 | #最长公共子串#
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
#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 vector<vector<int>> dp(str1.length() + 1, vector<int>(str2.length() + 1, 0)); int length = 0; int pos = 0; for(int i = 0; i < str1.length(); i++){ for(int j = 0; j <str2.length(); j++){ if(str1[i] == str2[j]){ dp[i + 1][j + 1] = dp[i][j] + 1; }else{ dp[i][j] = 0; } if(dp[i + 1][j + 1] > length){ length = dp[i + 1][j + 1]; pos = i; } } } return str1.substr(pos - length + 1, length); } };
C++动态规划方法解最长公共子串