您的位置:首页 > 其它

kmp算法

2017-02-20 19:53 351 查看
自己整理的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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: