自己整理的kmp算法,幫助自己理解。
關鍵是next算法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char a[1000050], b[1000050];
int next[1000050];
void getnext();
int kmp();
int main()
{
int t;
while(scanf("%s", a) != EOF)
{
scanf("%s", b);
memset(next, 0, sizeof(next)); //對next數組清零
getnext();
t = kmp();
printf("%d\n", t);
}
return 0;
}
void getnext() //next函數
{
int i = 0, j = -1;
next[0] = -1;
int t = strlen(b);
while(i < t)
{
if(j == -1 || b[i] == b[j])
{
++i;++j;
if(b[i] != b[j]) next[i] = j; //如果不同next值爲j
else
next[i] = next[j]; //如果相同next值相同
}
else j = next[j];
}
}
int kmp()
{
int i = 0, j = 0, t1, t2;
t1 = strlen(a);
t2 = strlen(b);
while(i < t1 && j < t2)
{
if(j == -1 || a[i] == b[j])
{
++i;
++j;
}
else j = next[j];
}
if(j == t2) return i - t2 + 1;
else return -1;
}