#include <stdio.h>
#include<string.h>
void next(char*,int*,int);
int KMP(char *s, char *t,int *next);
void next(char *str,int *next,int size){
next[0]= 0;
int i=0,j=1;
while(j< size){
if(str [i] == str[j] )
next[j++]= ++i;
else{
while( i>0 && str[i] != str[j] )
i = next[i-1] ;
if(i == 0 && str[i] != str[j] )
next[j++] = 0;
}
}
}
int
KMP(char *s, char *t,int *next){
int size_s = (int)strlen(s)-1;
int size_t = (int)strlen(t)-1;
int i=0,j=0;
while( i<size_s && j<size_t){
if(s[i] == t[j]) //i是主串 !!
i++,j++;
else {
if(j)
j= next[j-1];
i++;
}
}
if(j >size_t)
return i-size_t;
else return 0;
}
int main(){
char str[64];
fgets(str,64,stdin);
int size = (int)strlen(str)-1; // 串长度 不包含NUL
int t[size] ;
next(str,t,size);
int a = KMP(str,"abc",t);
printf("%d \n",a);
return 0;
}
KMP算法自练(下标0开始 )
最新推荐文章于 2023-02-15 15:40:39 发布