#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[]);
void gets_next_arry(Bunch &L,int news[Max]);
int KMP(Bunch &L1,Bunch &L2,int next[]);
int main()
{
Bunch L1,L2;
char t[Max];
gets(t);
creat(L1,t);
printlist(L1);
gets(t);
creat(L2,t);
printlist(L2);
int next[L2.length];
gets_next_arry(L2,next);
for(int i=0;i<L2.length;i++)
{
cout<<next[i]<<" ";
}
cout<<endl;
cout<<"L2在L1的"<<KMP(L1,L2,next)<<"个位置"<<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;
}
void gets_next_arry(Bunch &L,int next[])
{
next[0]=-1;
int k=-1;
int i=0;
while(i<L.length)
{
if((k==-1)||(L.a[i]==L.a[k]))
{
i++;
k++;
if(L.a[i]!=L.a[k])
{
next[i]=k;
}
else
{
// k=next[k];不要改变K的值
next[i]=next[k];
}
}
else
{
k=next[k];
}
}
}
int KMP(Bunch &L1,Bunch &L2,int next[])
{
int i=0,j=0;
while((j<L2.length)&&(i<L1.length))
{
if(L1.a[i]==L2.a[j]||(j==-1))
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==L2.length)
{
return i-j+1;
}
else
{
return -1;
}
}
优化next数组后的 KMP算法
最新推荐文章于 2024-08-05 09:05:25 发布