对于两个字符串A和B,A的前i位和B的前j位的最大公共子序列必然是所求解的一部分,设dp[i][j]为串A前i位和B串前j位的最长公共子序列的长度,则所求答案为dp[n][m],其中n,m分别为字符串A和B的长度,若A[i]=B[j],则该元素可以作为之前构造的公共子序列的下一位元素,dp[i][j]=dp[i-1][j-1]+1,同时判断当前记录的最长子串的结果maxlen与dp[i][j]的大小,若是大于当前的最大值maxlen,则更新maxlen的值,同时记录索引位置index。直到所有遍历完毕,得到最长子串的末尾索引和长度,可以求取子串。
代码如下:
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 len1=str1.size();
int len2=str2.size();
vector<vector<int>>dp(len1+1,vector<int>(len2+1));
int index=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(dp[i][j]>maxlen)
{
maxlen=dp[i][j];
index=i-1;
}
}
}
}
return str1.substr(index-maxlen+1,maxlen);
}
};