KMP.H #ifndef KMP_H_H #define OK 0 #define ERROR -1 #define MAX_LENGTH 255 typedef unsigned char SString[MAX_LENGTH + 1]; //第0个位置存放串的长度 int sstr_assign(SString, const char*); int sstr_print(SString); int print_nextval(SString, int*, int); void get_nextval(SString, int*); int get_next(SString, int*); int index_KMP(SString, SString, int, int*); #endif KMP.CPP #include<stdio.h> #include<stdlib.h> #include"KMP.h" //产生一个SString类型的串,其值等于sstr int sstr_assign(SString T, const char *sstr) { int ix = 0; while(sstr[ix] != '/0') { T[ix + 1] = sstr[ix++]; //如果空间耗尽,则不再复制。 if(ix == MAX_LENGTH) break; } //保存串的长度 T[0] = ix; return OK; } int sstr_print(SString T) { int cnt = T[0]; int ix = 1; while(cnt-- > 0) { printf("%c",T[ix++]); } printf("/n"); return OK; } void get_nextval(SString T, int *nextval) { int i = 1; int j = 0; nextval[1] = 0; while(i < T[0]) { if(0 == j || T[i] == T[j]) { i++; j++; if(T[i] != T[j]) { nextval[i] = j; } else nextval[i] = nextval[j]; } else j = nextval[j]; } } int get_next(SString T, int *next) { int i = 1; int j = 0; next[1] = 0; while(i < T[0]) { if(0 == j || T[i] == T[j]) { i++; j++; next[i] = j; } else j = next[j]; } return OK; } int index_KMP(SString T, SString S, int pos, int *next) { if(pos < 1 || pos > T[0] || 0 == T[0] || 0 == S[0]) return ERROR; int ix = pos; int jx = 1; while(ix <= T[0] && jx <= S[0]) { if(jx == 0 || T[ix] == S[jx]) { ix++; jx++; } else jx = next[jx]; } if(jx > S[0]) return ix - S[0]; return OK; } int print_nextval(SString T, int *nextval, int n) { for(int i = 1 ; i <= n ; i++) printf("%3d", i); printf("/n"); for(i = 1 ; i <= n ; i++) printf("%3c", T[i]); printf("/n"); for(i = 1 ; i <= n ; i++) printf("%3d", nextval[i]); printf("/n"); return OK; }