#include<iostream>
#include<string>
using namespace std;
void GetNext(string& T, int* next)
{
int i = 0;
int j = -1;
next[0] = -1;
int tmp = T.size();
while (i < tmp)
{
//T[j]为前缀单个字符,T[i]为后缀单个字符
if ((j == -1) || (T[j] == T[i]))
{
++i;
++j;
next[i] = j;
}
else
{
//j回溯
j = next[j];
}
}
}
int GetKMP(string& X, string& T)
{
int* next = new int[100];
//i用于主串S当前位置的下标值
int i = 0;
//字串T中当前位置的下标值
int j = 0;
GetNext(T, next);
int tmp1 = T.size();
int tmp2 = X.size();
while ((i < tmp2) && (j < tmp1))
{
//两字母相等则继续
if ((j == -1) || (X[i] == T[i]))
{
++i;
++j;
}
else
{
j = next[j];
}
}
delete[] next;
if (j == tmp1)
{
return i - j;
}
else
{
return -1;
}
}
int main()
{
string X = "abcababca";
string T = "cababc";
cout << GetKMP(X, T) << endl;
return 0;
}
//两字母相等则继续
if ((j == -1) || (X[i] == T[i]))
这里的T[ i ] 应该是 T[ j ]:
//两字母相等则继续
if ((j == -1) || (X[i] == T[j]))
感谢,下次一定小心