KMP 1234567891011121314151617181920212223242526272829303132333435363738394041424344#include<cstdio>#include<cstring>void get_next(char *p,int *next){ int pLen = strlen(p); next[0] = -1; int k = -1,j = 0; while(j < pLen - 1){ if(k == -1 || p[j] == p[k]){ j ++; k ++; next[j] = k; } else { k = next[k]; } }}int kmp(char *s, char * p, int *next){ int sLen = strlen(s); int pLen = strlen(p); int i = 0, j = 0; while(i < sLen && j < pLen){ if(j == -1 ||s[i] == p[j]){ i ++; j ++; } else { j = next[j]; } } if(j == pLen){ return i - j; } else return -1;}int main(){ char s1[123] = "ggbbaacda"; char s2[123] = "aadd"; int next[123] ; get_next(s2,next); printf("%d\n",kmp(s1,s2,next)); return 0;}