//dp问题:最长公共子串
#include<iostream>
#include<cstring>
using namespace std;
void maxSubstr(string str1,string str2,int &max,int &pos)
{
//两个子串至少有一个为空时,直接返回空
if(str1==""||str2=="")
{
cout<<"最长公共子串为空!"<<endl;
return;
}
int len1=str1.length();
int len2=str2.length();
//用len记录两个字符串较长的那一个
int len;
if(len1>len2)
{
len=len1;
}
else
{
len=len2;
}
int dp[len][len];//可以自己画一个矩阵,便于理解哦
for(int i = 0; i < len;i++)
{
for(int j = 0; j<len; j++)
{
dp[i][j]=0;
}
}
for(int i = 0; i < len;i++)
{
for(int j = 0; j<len; j++)
{
if(str2[i] == str1[j])
{
if(i == 0||j == 0)//首行或者首列
{
dp[i][j] = 1;
}
else
{
dp[i][j]=dp[i-1][j-1] + 1;//当前公共子串长度加一
}
if(dp[i][j] > max)//当前公共子串的长度比原来的最长子串长
{
max=dp[i][j];
pos=i;
}
}
}
}
}
int main()
{
string str1,str2;
cout<<"请输入第一个字符串:"<<endl;
getline(cin,str1);
cout<<"请输入第二个字符串:"<<endl;
getline(cin,str2);
//max为当前最长的公共子串的长度,pos为最长公共子串的最后一个字符在原串(str1)中的位置
int max=0,pos=0;
maxSubstr(str1,str2,max,pos);
cout<<"最长公共子串为:"<<str1.substr(pos-max+1,max)<<endl;
return 0;
}
10-20
313
10-12
219
03-01
154