关于KMP,虽然已经理解了,并且能记住实现思路,但是在每次遇到需要写出代码的时候总会出现问题,整理一下代码,加深一下映像。
上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void get_next(char* str1,int next[]) // From the array next[];
{
int i = 1, j = 0; // point1
next[0] = strlen(str1); // next[0] will not be used, so we can store the length of str1 in there.
next[1] = 0;
while(i<next[0])
{
if(j == 0||str1[i-1] == str1[j-1])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int Index_kmp(char* str2,char* str1) //
{
int len = strlen(str1)+1;
int next[len];
get_next(str1, next);
for(int i = 0; i<len; i++)
{
printf("%d\t",next[i]);
}
puts("\n");
int i = 1, j = 1; //====> point2
while(i <= strlen(str2) && j <= next[0])
{
if(j ==0 || str2[i-1] == str1[j-1])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if(j > next[0])
{
return i - next[0]; //match maybe should return i-next[0]-1;
}
else
{
return -1;
}
}
void main()
{
char str2[] = "NLZASTSODJRFTQE";
char str1[] = "ODJR";
int num = Index_kmp(str2, str1);
printf("%d\n",num);
}
#if 0 // a better kmp algorithm
//kmp++
void Next(char*T,int *next){
int i=1;
next[1]=0;
int j=0;
while (i<strlen(T)) {
if (j==0||T[i-1]==T[j-1]) {
i++;
j++;
if (T[i-1]!=T[j-1]) {
next[i]=j;
}
else{
next[i]=next[j];
}
}else{
j=next[j];
}
}
}
$)AD#J=4.#:a a a a a a a b
next1$)A#:0 1 2 3 4 5 6 7
next2$)A#:0 0 0 0 0 0 0 7
#endif