初看kmp算法的时候有点模糊,第一次就根本没明白过。
仔细的推敲。找相关类似的问题。现在把源程序贴出来供大家参考。
关键一点就是要了解next函数的构造,以及为什么要这么做。
在数据结构81页中的next推倒,不过不是很好理解。
其中next是按1开始。伪代码的写法
演示下推导的思路(按书上的从1开始的next求法):
j | 1 2 3 4 5 6 7 8
---------------------------------------------
模式串 | a b a a b c a c
next[j] | 0 1 1 2 2 3 1 2
其中j=1时,是第一个字符'a' 而a前面没有匹配的字符所以next[1]=0;
当 j=2时,是第二个字符'b',而b前面只有一个字符,'a',a又是第一个字符不能和自己匹配,所以next[2]=1;
当j=3时,是第三个字符'a', 前面的b和第一个字符a不匹配,所以next[3]=1;
当j=4时,是第四个字符'a',它前面的字符是a,和第一个字符a是匹配的,所以+1
得到next[4]=2;
同理,j=5时,前面是a.和第一个字符还是匹配的.next[5]=2 ,//(一个字符长度+向前面移动一个单位)
j=6时,前面字符是abaab可以取到最长的子串是ab与第一个字符开始匹配,匹配成功next[6]=3 //最长子串长2+向前移动1个单位得到3
结合这,把83页get_next()函数仔细的把数带进去推一次就不会那么模糊了
#include<string.h>
#include<conio.h>
#define MAX 250
void get_next(const char *T,int *next)//next
{
int i=0,j=-1;
next[0] = -1; //next[0] = -1 跟数组下表相配套,从0开始
while(i < strlen(T))
{
if(j == -1 || T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else
{
j=next[j];
}
}
}
int Index_KMP(const char *S, const char *T)//KMP
{
int i=0, j=0;
int next[MAX];
get_next(T,next);
while(i < strlen(S) && j < strlen(T))
{
if(j == 0 || S[i] == T[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j >= strlen(T)) return i-strlen(T);
else return 0;
}
void main()
{
int pos;
char str1[MAX];//主串
char str2[MAX];//模式串
printf("input first string:");
gets(str1);
printf("input second string:");
gets(str2);
pos=Index_KMP(str1,str2);
printf("匹配位置在主串第%d个字符之后的位置",pos);
getch();
}