KMP算法实现

核心是模式串next数组的生成

#include <stdio.h>
#include
<string.h>
#define NS 100
int strpos( char s1[] , char s2[] ,int N[]);
void next( char s2[],int N[]);
int main(int argc, char *args[] )
{
int i = 0,k = 0;
int N[NS] = {0};
next( args[
2],N );
printf(
"%d\n",strpos(args[1],args[2],N));
return 0;
}

int strpos( char s1[],char s2[],int N[])
{
int i = 0,j = 0,l=strlen(s1),l2=strlen(s2);
if(l2 > l)
{
printf(
"Error,pattern string is longer than source string.\n");
return -2;
}
while( i < l )
{
if(s2[j] == '\0')
{
break;
}
if(s2[j] == s1[i])
{
j
++;
i
++;
}
else
{
i
-= N[j];
j
= 0;
}
}
return (j > 0 && s2[j] =='\0') ? i-j : -1;
}
//模式串对应的回退数组,标记着主串在和模式串每个位置匹配失败后,主串应该回退多少位再和模式串逐一匹配
void next(char s2[],int N[])
{
N[
0] = -1;
N[
1] = 0;
int i = 1,j = -1,l=strlen(s2);
while( i < l )
{
if(j== -1 || s2[i] == s2[j])
{
j
++;
i
++;
N[i]
= j;
}
else
{
j
= N[j];
}
}
}

#kmp abababacb ababacb
2

编译执行 kmp abababacb ababacb

结果为2

posted @ 2011-04-08 21:35  一缕青烟  阅读(215)  评论(0编辑  收藏  举报