KMP算法练习
#include <stdio.h> getNext(char str[],int n, int next[]){ int i, j; i = 1; j = 0; next[0] = -1; next[1] = 0; while(i < n){ if(str[i] == str[j]){ i++; j++; next[i] = j; } else if(j == 0){ i++; next[i] = 0; } else j = next[j]; } } KMP(char content[], int n, char str[], int m, int next[]){ int i, j; i = 0; j = 0; while(i < n && j < m){ if(content[i] == str[j]){ i++; j++; } else if(j == 0){ i++; } else{ j = next[j]; } } if(j == m) printf("%d", 1); else printf("%d", 0); } main(){ int i; int next[10]; char str[] = {'a', 'b', 'c', 'a', 'b', 'c', 'a', 'a', 'a'}; char content[] = {'r', 'a', 'b', 'c', 'a', 'A', 'c', 'a', 'a', 'a', 'c'}; getNext(str, 9, next); for(i = 0; i < 9; i++) printf("%d ",next[i]); printf("\n"); KMP(content, 11, str, 9, next); }