http://www.slyar.com/blog/kmp.html
代码如下:
#include <iostream>
using namespace std;
void get_next(char* T, int* next)
{
int i, j;
i = 0;
j = -1;
next[0] = -1;
while(T[i] != '\0')
{
if (j == -1 || T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
int Index_KMP(char* S, char* T, int length1, int length2, int pos)
{
int i = pos;
int j = 0;
int next[255];
get_next(T, next);
while(i < length1 && j < length2)
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j >= length2)
return i-length2;
else
return 0;
}
void main()
{
char S[] = "uiababcdefgh";
char T[] = "ababc";
int index = 0;
index = Index_KMP(S, T, 12, 5, 0);
cout<<index;
}