#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int *buildNext(char *p);
int match(char *P, char *T);
int main(int argc, char *argv[])
{
const char *T = "thisiathekmpteststring";
const char *P = "test";
int n = match((char *)P, (char *)T);
printf("T : %s\n", T);
printf("P : %s\n", P);
printf("n : %d\n", n);
system("pause");
return 0;
}
int *buildNext(char *p)
{
int m = strlen(p), j = 0;
int *next = new int[m];
int t = next[0] = -1;//约定
while (j < m - 1)
{
if (t < 0 || p[j] == p[t]) {
j++; t++;
next[j] = t;
}
else {
t = next[t];
}
}
return next;
}
int match(char *P, char *T)
{
int *next = buildNext(P);
int p_n = strlen(P), i = 0;
int t_n = strlen(T), j = 0;
while (i < p_n && j < t_n)
{
if (i < 0 || T[j] == P[i]) {
j++; i++;
}
else {
i = next[i];
}
}
delete[] next;
return j - i;
}