KMP算法
来源:互联网 发布:鸦片战争 知乎 编辑:程序博客网 时间:2024/05/01 04:16
#include <stdio.h>struct SeqString { int MAXNUM; int n; char *c;};typedef struct SeqString * PSeqString;PSeqString createNullStr_seq(int m){ PSeqString pstr = (PSeqString)malloc(sizeof(struct SeqString)); if(pstr !=NULL) { pstr->c = (char *)malloc(sizeof(char)*m); if(pstr->c) { pstr->n=0;pstr->MAXNUM=m; return (pstr); } else free(pstr); } printf("Out of space!/n"); return NULL;}makeNext(PSeqString p,int *next){ int i=0,k=-1; next[0] = -1; while(i<(p->n-1)) { while(k>=0 && p->c[i]!=p->c[k]) k=next[k]; i++;k++; if(p->c[i] == p->c[k]) next[i]=next[k]; else next[i]=k; }}int pMatch(PSeqString t,PSeqString p,int *next){ int i=0,j=0; while(i < p->n && j < t->n) { if( i==-1 || p->c[i] == t->c[j]) {i++;j++;} else i=next[i]; } if(i > p->n) return (j - p->n + 1); else return(0);}int main(){ PSeqString s; int next[9],i=0; s = createNullStr_seq(9); s->c[0] = 'a'; s->c[1] = 'b'; s->c[2] = 'c'; s->c[3] = 'a'; s->c[4] = 'b'; s->c[5] = 'b'; s->c[6] = 'a'; s->c[7] = 'b'; s->c[8] = 'c'; s->n = 9; makeNext(s,next); for(i=0;i<9;i++) printf("%d/n",next[i]);}