我也不是很懂,以后懂了再来改吧。
#include <iostream>
#include <string>
using namespace std;
int* GetNext(string T)
{
int *next = new int;
int i = 1;
int j = 0;
next[1] = 0;
while (i < T.length())
{
if (j == 0 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
return next;
}
int Index_KMP(string S, string T, int pos)
{
int *next = GetNext(T);
int i = pos; //操作人员输入需要从第几位查起
int j = 1;
while (i < S.length() && j < T.length())
{
if (S[i] == T[j])
{
i++;
j++;
}
else {
j = next[j];
}
}
if (j > T.length())
return i - T.length();
else
return -1;
}