#include <iostream>
#include <cstring>
using namespace std;
void getNext(const char *p, int next[]);
int KmpSearch(const char *s, const char *p, int next[]);
int main(void){
const char *s = "aabaabaaf";
const char *p = "aabaaf";
int next[strlen(p)];
getNext(p, next);
int result = KmpSearch(s, p, next);
if (result != -1)
{
cout<<"结果为"<<result + 1<<endl;
}
else
cout<<"找不到相同的字符串!"<<endl;
return 0;
}
void getNext(const char *p, int next[])
{
int j = 0;
next[0] = 0;
for (int i = 1; i < strlen(p); i++)
{
while (j > 0 && p[i] != p[j])
{
j = next[j - 1];
}
if (p[i] == p[j])
{
j++;
}
next[i] = j;
}
}
int KmpSearch(const char *s, const char *p, int next[]){
int i = 0;
int j = 0;
int len_s = strlen(s);
int len_p = strlen(p);
while (i < len_s && j < len_p)
{
if (j == 0 || s[i] == p[j])
{
i++;j++;
}
else
j = next[j - 1];
}
if (j >= len_p)
{
return (i - len_p);
}
else return -1;
}