题目
题目描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
示例1
输入
"1AB2345CD","12345EF"
返回值
"2345"
解析
动态规划
dp[i][j],i代表str1[i]结尾的串,j代表str2[j]结尾的串,dp[i][j]代表此时最长公共子串长度
str1[i-1]==str2[j-1] : dp[i][j]=dp[i-1][j-1]+1;
str1[i-1]!=str2[j-1] : dp[i][j]=0;
用len_max,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(),len2=str2.size();
if(len1==0||len2==0){
return "";
}
vector<vector<int>> dp(len1+1,vector<int>(len2+1,0));
int len_max=0,index=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]>len_max){
len_max=dp[i][j];
index=i-len_max;
}
len_max=max(dp[i][j],len_max);
}else{
dp[i][j]=0;
}
}
}
return str1.substr(index,len_max);
}
};