KMF算法的实现过程

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxsize 100

typedef struct {
char chr[maxsize];
int len;
}sqstring;

void get_next(sqstring patternT, int next[]);
int kmfindex(sqstring patternS, sqstring patternT);

void get_next(sqstring patternT, int next[]){
int j = 0;
int k = -1;
next[0] = -1;

while(j < patternT.len){
if (k == -1 || patternT.chr[j] == patternT.chr[k]) {
j++;
k++;
next[j] = k;
}
else {
k = next[k];
}

}


}
int kmfindex(sqstring patternS,sqstring patternT){
int next[maxsize];
int j = 0;
int i = 0;
int v;

get_next(patternT,next);
while(j < patternT.len && i < patternS.len){
if( j == -1 || patternS.chr[i] == patternT.chr[j]){
i++;
j++;
}
else j = next[j];
}
if(j >= patternT.len) v = i - patternT.len;
else v = -1;
return v;
}

int main(){
int k;
sqstring patternS = {"hello this is kmf,do want to know about it, please try to look carefullycareful"};
sqstring patternT ={"carefullycareful"};
patternS.len = strlen(patternS.chr);
patternT.len = strlen(patternT.chr);

freopen("C:\\Users\\fangfanglou\\Desktop\\kmf.txt", "r", stdin);
freopen("C:\\Users\\fangfanglou\\Desktop\\kmf.txt", "w", stdout);
k = kmfindex(patternS, patternT);
printf("\n 找到对应字符串的位置了: %d\n", k);
printf("very 棒球");
fclose(stdin);
fclose(stdout);
return 0;
}

猜你喜欢

转载自www.cnblogs.com/alifengfeng/p/9226377.html