#include <iostream>
#include <string>
using namespace std;
void getNext(string find, int *&next) {
next[0] = -1;
int i = 0, j = -1;
int length = find.length();
while (i < length - 1) {
if (j == -1 || find[i] == find[j]) {
i++;
j++;
if (find[i] != find[j]) {
next[i] = j;
}
else {
next[i] = next[j];
}
}
else j = next[j];
}
}
int kmp(string text, string find) {
int ans = -1;
int length = find.length();
int *next = new int[length];
getNext(find, next);
for (int i = 0; i < length; i++) {
cout << next[i] << " ";
}
cout << "\n";
int i = 0, j = 0;
int lengthT = text.length();
while (i < lengthT && j < length) {
if (j==-1 || text[i] == find[j]) {
i++;
j++;
}
else j = next[j];
}
if (j == length)ans = i - j;
else ans = -1;
delete[] next;
return ans;
}
int main() {
string text = "ababcdeabdfe";
string find = "abd";
int ans = kmp(text, find);
cout << ans;
return 0;
}