#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;
}
模式串和主串最大相同的长度,以及他在主串中的位置
最新推荐文章于 2023-01-31 22:53:02 发布