//对字串进行处理,得到next表
#include <stdio.h>
#define N 50005
int ans,next[N],P[N],M[N];
void GetNext(int *P){
next[0]=-1;
for( int i = 1,j=-1 ; P[i] ; i++ ) {
if( P[i] == P[j+1] ){
j++;
next[i]=j;
}
else{
while( j!=-1 && P[i] != P[j+1] )
j=next[j];
next[i] = j;
}
}
}
void Kmp(int *M,int *P){
GetNext(P);
for(int i = 0, j = -1; M[i] ; i++ ){
while( j !=-1 && M[i] != P[j+1] )
j = next[j] ;
if( j == -1 && M[i] !=P[j+1] )
continue;
else
j++;
if( P[ j+1 ] == 0 )
ans++;
}
}
数据结构之KMP算法
最新推荐文章于 2022-11-27 09:22:59 发布