具体的参照该网址:
https://www.cnblogs.com/zhangtianq/p/5839909.html
实现如下:不过解释 或者说怎么实现的在上面网址
1 #include<cstdio> 2 #include<cstring> 3 #define N 10 4 5 int next[N] = {0}; 6 7 void getNext(char P[]); 8 9 int main(void) { 10 char T[] = "abcbabcd"; 11 char P[] = "abc"; 12 int i = 0, j = 0;//i为主串的指针位置,j为模式串指针位置 13 int len_P = strlen(P); 14 int len_T = strlen(T); 15 16 getNext(P); 17 while (i < len_T && j < len_P) { 18 if (j == -1 || T[i] == P[j]) { i++; j++; } 19 else j = next[j]; 20 } 21 22 if (j == len_P) printf("%d", i - j); 23 else printf("-1"); 24 } 25 26 void getNext(char P[]) { 27 next[0] = -1; 28 29 int j = 0, k = -1; 30 int len = strlen(P);
//p[k]是前缀,p[j]是后缀 31 /* 32 while (j < len - 1) { 33 if (k == -1 || P[j] == P[k]) next[++j] = ++k; 34 else k = next[k]; 35 }//其实这个循环还是可以优化 如下: 36 */ 37 while (j < len - 1) { 38 if (k == -1 || P[j] == P[k]) { 39 if (P[++j] == P[++k]) next[j] = next[k]; 40 else next[j] = k; 41 } 42 else k = next[k]; 43 } 44 45 }