参考理解:https://oi-wiki.org/string/kmp/
https://blog.csdn.net/daaikuaichuan/article/details/80719203
构造next数组
void get_next(int next_[], char str[]) {
int len = strlen(str);
next_[0] = 0;
for (int i = 1; i < len; i++) {
/*j表示上一个匹配的长度, j - 1就是j长度的前缀的末尾下标*/
int j = next_[i - 1];
/*如果不匹配, j == 0 或 不匹配时退出循环*/
while (j > 0 && str[i] != str[j]) j = next_[j - 1]; //向前回溯查找
if (str[i] == str[j]) j++;
next_[i] = j;
}
}
KMP算法应用
在字符串中查找子串
vector<int> KMP(char str[], char str1[], int next_[]) {
vector<int> vec;
int len = strlen(str);
int j = 0; //初始
for (int i = 0; i < len; i++) {
if (str[i] == str1[j]) {
j++;
} else if (j) { // 如果j == 0, 且不匹配直接跳过
j = next_[j - 1]; //回溯, 注意不是 j = next_[j] - 1
i--;
}
if (j == strlen(str1)) { //匹配成功
vec.push_back(i - j + 1); //记录匹配位置
j = 0; //重新匹配余下的字符串
}
}
return vec;
}
字符串的周期
统计每个前缀的出现次数
PTA好后缀:https://blog.csdn.net/qq_45349225/article/details/109644783