模式串和主串最大相同的长度,以及他在主串中的位置

#include<iostream>
#include<stdio.h>
using namespace std;
const int Max=50;

typedef class NOde
{
public :
 char a[Max];
 int length;
}Bunch;
void printlist(Bunch &L);
void creat(Bunch &L,char t[]);
Bunch the_same_max_length(Bunch &L1,Bunch &L2,int &position,int &length);

int main()
{

 int position,length;
 Bunch L1,L2;
 char t[Max];
 gets(t);
 creat(L1,t);
 printlist(L1);
 gets(t);
 creat(L2,t);
 printlist(L2);
 Bunch L=the_same_max_length(L1,L2,position,length);
 cout<<"最长相同字符串为"<<endl;
 printlist(L);
 cout<<"位于主串的第"<<position+1<<"个位置"<<endl;
 cout<<"他的长度为"<<length<<endl;
 return 0;
}


void creat(Bunch &L,char t[])
{
 int i=0;
 while(t[i]!='\0')

 {
     L.a[i]=t[i];
     i++;
 }

 L.a[i]='\0';
 L.length=i;
}


void printlist(Bunch &L)
 {

     int i=0;
     while(L.a[i]!='\0')
     {
         cout<<L.a[i];
         i++;
     }
     cout<<endl;
 }

Bunch the_same_max_length(Bunch &L1,Bunch &L2,int &position,int &length)//L2是模式串
 {
     int i=0,j=0,k=0;
     position=-1;
     length=0;
     int len;
     while(i<L1.length)

     {
         k=0;
         while(j+k<L2.length)

             {

                 len=0;
                 while((L1.a[i+k]==L2.a[j+k])&&(i+k<L1.length)&&(j+k<L2.length))

                 {
                      k++;
                      len++;
                 }

                 if(len>length)

                     {
                         length=len;
                         position=i+k-len;
                     }

                 k++;

             }

         i++;
     }

     i=position;
     Bunch temp;
     j=0;
     while(j<length)
     {
         temp.a[j]=L1.a[i];
         i++;
         j++;
     }
     temp.a[j]='\0';
     return temp;

 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值