题解 | #最长公共子串#
最长公共子串
http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
最长公共子串VS最长公共子序列
第一个是连续的子串,第二个是非连续的子串
最长公共子串:dp[i][j]表示长度为i的字符串和长度为j的字符串,以i,j作为最长公共子串结尾的最大长度。
dp[i][j]=dp[i-1][j-1]+1 如果相等 dp[i][j]=0 如果不等
最长公共子序列:dp[i][j]表示长度为i的字符串和长度为j的字符串,它们的最长公共子序列。
dp[i][j]=dp[i-1]dp[j-1]+1 如果相等 dp[i][j]=max(dp[i-1][j],dp[i][j-1]) 如果不等
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();
int dp[5001][5001]={0};
string ans="";
int index=0,maxlen=-1;
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;
}
}else{
dp[i][j]=0;
}
}
}
for(int w=index-maxlen;w<index;w++)
{
ans+=str1[w];
}
return ans;
}
};