最大公共子串求法与最大公共子序列类似,均可采用动态规划的思想
if(str1[i]==str2[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=0;
代码如下:
/**
*Copyright @ 2019 Zhang Peng. All Right Reserved.
*Filename:
*Author: Zhang Peng
*Date:
*Version:
*Description:
**/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int MaxCommonStr(string str1, string str2)
{
int len1 = str1.size();
int len2 = str2.size();
int result = 0;
if (len1 == 0 || len2 == 0)
return result;
vector<vector<int >> dp(len1+1, vector<int>(len2+1, 0));
int start, end;
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;
else
dp[i][j] = 0;
if (result < dp[i][j])
{
result = dp[i][j];
start = i;
end = j;
}
}
}
//dp表显示
cout << "dp: " << endl;
for (int i = 0; i < dp.size(); i++)
{
for (int j = 0; j < dp[0].size(); j++)
{
cout << dp[i][j] << " ";
}
cout << endl;
}
//回溯求解公共子串
string str;
while (start >= 0 && end >= 0)
{
if (dp[start][end] != 0&&dp[start-1][end-1]+1==dp[start][end])
{
str.insert(str.begin(), str1[start-1]); //这里使用start-1是因为前面建立dp表的时候比较的是str1[i-1]==str2[j-1],前面有1位的偏移
start--;
end--;
}
else
break;
}
cout << "最大公共子串: " << str << endl;
return result;
}
int main()
{
string str1= "sdfkjsdf";
string str2 = "fkojsd";
cout << "原字符串1为: " << str1 << endl;
cout << "原字符串2为: " << str2 << endl;
cout <<"最大公共子串长度为: "<< MaxCommonStr(str1, str2) << endl;
system("pause");
return 0;
}