KMP算法
include <stdio.h>
include <stdlib.h>
include <string.h>
// 这个还是有些问题的!!
void
get_next_flaw(char * t, int next[])
{
int i, j;
i = 0; j = -1; next[i] = -1;// 先规定好最初始的next值
while (i < strlen(t))
{
if (j == -1 || t[i] == t[j]) {// 如果是初始值j==0 ????
++i; ++j;
next[i] = j;
} else {
j = next[j];
}
}
}
void
get_next(char * t, int next[])
{
int i, j;
i = 0; j = -1;
next[i] = j;// 先规定好最初始的next值
while (i <= strlen(t))
{
if (j == -1 // 初始条件,边界值
|| t[i] == t[j]) {
++i; ++j;
if (t[i] != t[j])
next[i] = j;
else
next[i] = next[j];
} else {
j = next[j];
}
}
}
int
index_kmp(char * s, char * t, int pos)
{
int i, j;
int * next;
int len1, len2;
next = malloc(sizeof(int) * strlen(t));
memset(next, 0, sizeof(int) * strlen(t));
len1 = strlen(s);
len2 = strlen(t);
get_next(t, next);
if 1
i = -1;
while (++i < strlen(t)) {
printf("%d\t", next[i]);
}
endif
i = pos-1; j = -1;
while (i < len1 && j < len2) {
if (j == -1 || s[i] == t[j]) {
++i; ++j;
} else {
j = next[j];
}
}
//free(next);
if (j >= strlen(t))
return i - strlen(t);
else
return -1;
}
int main()
{
char s, t;
int pos;
/01234567/
s = "acabaabaabcacaabc";
t = "abaabcac";
pos = index_kmp(s, t, 0);
printf("find at %d\n", pos);
getchar();
return 0;
}