今天简单的给大家介绍一下KMP算法,
#include "stdafx.h"
#include "string.h"
int Index_Kmp(char S[],char T[],int next[],int pos,int n,int m){
int i =pos-1;
int j=-1;
while( (i <n)&&(j <m)){
if(j==-1||S[i]==T[j]){
++i;++j;
}else{
j = next[j]-1;//J被回溯
}
for(int k=0;k<=i;k++){
printf("%c ",S[k]);
}
printf("\n");
for(int k=0;k<=i;k++){
if(k<i-j)
printf(" ");
else
printf("%c ",T[k+j-i]);
}
printf("\n");
if(j>=m)
return i- m;
}
return 0;
}
//求next数组
void makeNext(const char T[],int next[]){
int i =0;int j =-1;
next[0] = 0;
while(i<strlen(T)){
if(j==-1||T[i]==T[j]){
++i;++j;
next[i] = j+1;
}else{
j = next[j]-1;//J被回溯
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int pos =0;
int next[32]={0};
char S[]={'a','b','a','b','a','a','c','a','b','a','a','b','a','b','a','a','b','a','b','c','a','\0'};//原串
char T[]={'a','b','a','b','a','a','b','a','\0'};//目标串
int n = strlen(S);
int m = strlen(T);
makeNext(T,next);
pos =Index_Kmp(S,T,next,0,n,m);//返回原串在目标串中的起始位置
printf("%d\n",pos);
getchar();
return 0;
}
</pre><p></p><p>程序运行步骤如下:</p><p><pre name="code" class="cpp">a
a
a b
a b
a b a
a b a
a b a b
a b a b
a b a b a
a b a b a
a b a b a a
a b a b a a
a b a b a a c
a b a b a a b
a b a b a a c
a b
a b a b a a c
a
a b a b a a c
a b a b a a c a
a
a b a b a a c a b
a b
a b a b a a c a b a
a b a
a b a b a a c a b a a
a b a b
a b a b a a c a b a a
a b
a b a b a a c a b a a
a
a b a b a a c a b a a b
a b
a b a b a a c a b a a b a
a b a
a b a b a a c a b a a b a b
a b a b
a b a b a a c a b a a b a b a
a b a b a
a b a b a a c a b a a b a b a a
a b a b a a
a b a b a a c a b a a b a b a a b
a b a b a a b
a b a b a a c a b a a b a b a a b a
a b a b a a b a
a b a b a a c a b a a b a b a a b a b
a b a b a a b a