#include <iostream>
#include <vector>
#include <string>
//构建部分匹配表
std::vector<int> build_next(const std::string& patt) {
std::vector<int> next{ 0 };
int prefix_len = 0;
int i = 1;
while (i < patt.size()) {
if (patt[prefix_len] == patt[i]) {
prefix_len++;
next.push_back(prefix_len);
i++;
}
else {
if (prefix_len == 0) {
next.push_back(0);
i++;
}
else {
prefix_len = next[prefix_len - 1];
}
}
}
return next;
}
int kmp_search(const std::string& string, const std::string& patt) {
std::vector<int> next = build_next(patt);
int i = 0; // 主串中的指针
int j = 0; // 子串中的指针
while (i < string.size()) {
if (string[i] == patt[j]) { // 字符匹配,指针后移
i++;
j++;
}
else if (j > 0) { // 字符失配,根据next跳过子串前面的一些字符
j = next[j - 1];
}
else { // 子串第一个字符就失配
i++;
}
if (j == patt.size()) { // 匹配成功
return i - j;
}
}
return -1; // 匹配失败
}
int main() {
std::string string = "ababcabcacbab";
std::string patt = "abcac";
int index = kmp_search(string, patt);
if (index != -1) {
std::cout << "Pattern found at index " << index << std::endl;
}
else {
std::cout << "Pattern not found" << std::endl;
}
return 0;
}