#include<iostream>
#include<cctype>
int max(char *t,char *p,int m , int n);//t 为主串,长度为m,p为子串,长度为n
using namespace std;
int main(void)
{
char *t, *p;
t="hellohellohehehehl";
p="hello";
cout<<"please input a string t"<<endl;
//cin>>t;
cout<<"please input a string p"<<endl;
//cin>>p;
int i,j;
i=strlen(t);
j=strlen(p);
int sum=0;
max(t,p,i,j);
system("pause");
}
int max (char * t,char *p, int m, int n)
{
int row=m;
int col=n;
int ** c, **b;
c= new int *[m+1];
b=new int *[m+1];
for(int i=0; i<m+1; ++i)
{
c[i]=new int[n+1];
b[i]=new int[n+1];
}
for(int i=0;i<=m; ++i)
for(int j=0;j<=n; ++j)
{
b[i][j]=0;
}
for(int i=0; i<m+1; ++i)
for(int j=0; j<n+1; ++j)
{
c[i][j]=0;
}
for(int i=1; i<=m; ++i)//求公共子串
for(int j=1; j<=n; ++j)
{
if(t[i-1]==p[j-1])
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]=1;
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
b[i][j]=2;
}
else
{
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
cout<<"the maxString is length of "<<c[m][n]<<endl;
while((m>0)&&(n>0))//倒序输出公共串
{
if(b[m][n]==1)
{
cout<<t[m-1];//如想正序输出,需要建一个数组来保存。数组长度为c[m][n]
--m;
--n;
}
else if(b[m][n]==2)
{
--m;
}
else
{
--n;
}
}//end while
for(int i=0; i<=row;++i)
{
delete [] c[row];
delete [] b[row];
}
return 1;
}