求最大公共子串的算法

 

#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;
}
 
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值