next数组 void get_Next(char ch[], int length) { int j = -1; next[0] = -1; for (size_t i = 0; i < length; i++) { while (j!=-1&&ch[i]!=ch[j+1]) { j = next[j]; } if (ch[i] == ch[j + 1]) { j++; } next[i] = j; } } kmp算法 (比较text文本串内 含有?pattern字符串) bool kmp(char text[], char pattern[]) { int n=sizeof(text); int m = sizeof(pattern); get_Next(pattern, m); int j = -1; for (size_t i = 0; i < n; i++) { while (j != -1 && text[i] != pattern[j + 1]) { j = next[j]; } if (text[i] == pattern[j + 1]) { j++; } if (j == m - 1) { return true; } } return false; }