#include<stdio.h>
int length(char *str){
int i=0;
while(str[i]!='\0'){
i++;
}
return i;
}
void getNextval(char *str,int nextval[]){
int i=0,j=-1;
nextval[0]=-1;
while(i<length(str)){
if(j==-1||str[i]==str[j]){
i++;
j++;
if(str[i]==str[j]){
nextval[i]=nextval[j];
}else{
nextval[i]=j;
}
}else{
j=nextval[j];
}
}
}
int KMP(char *txt,char *str){
int i=0,j=0;
int nextval[length(str)];
getNextval(str,nextval);
while(i<length(txt)&&j<length(str)){
if(j==-1||txt[i]==str[j]){
i++;
j++;
}else{
j=nextval[j];
}
}
if(j>=length(str)){
return i-length(str);
}else{
return -1;
}
}
int main(){
char txt[]="abaabc";
char str[]="aa";
int temp=KMP(txt,str);
if(temp==-1){
printf("Not found.\n");
}else{
printf("The index is %d.\n",temp);
}
return 0;
}
KMP算法改进(C语言)
最新推荐文章于 2022-03-30 17:57:50 发布