Just learned in the past when the daze, a look at the circle, a few days ago picked up when found not
So the study of two days, a serious setback in self-esteem, today, when suddenly a spark, incredibly
Feel like understand, and then again figured up finally I understand hehe!
0 1 2 3 4 5 6 7 8 9
Main string: A b c D e a B c D f
I
0 1 2 3 4 5 6 7 8 9
Pattern string: C D F
J
i=4 when e!=f match fails the traditional character match is to let i=3,j=0 continue matching, i++,j=0.
This kind of matching is easy to understand, but many times more useless backtracking comparisons (e.g. i=3,j=0)
So the KMP algorithm turned out to be true, I really admire the man who invented this algorithm, too dick ...
Look at the pornography algorithm using the mode of sliding patterns, effectively avoiding the useless backtracking
-------------------------------------------------------------------
My understanding of the KMP algorithm
Two of strings
0 1 2 3 4 5 6 7
A b c A b a a B A E F (with I pointing character)
A B A E (with J pointing character)
i=3,4,5 equals j=0,1,2 and i=6 is not equal to j=3
At this time the traditional idea is to compare j=0,i=4 in turn. The KMP algorithm solves the problem of character matching by the way of moving pattern string.
Because i=3,4,5 equals j=0,1,2.
So i=5 equals j=2.
and j=0 equals j=2 do not need to match j=0 and i=4 invalid match, directly move the pattern string to the right two bits can be
Question one: Why J=0 and i=4 are invalid matches?
1. Pattern string known j=0 not equal to J=1
2.i=4 equals J=1 and j=0 is not equal to J=1 so j=0 designation does not equal i=4
So don't compare
Question two: Why move two bits to the right?
Distance l=length (pattern string)-next[j] (minus is always the largest element in the array);
A B A E
next[j]= 0 1 1 2
The realization of the algorithm of looking at pornography
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int Len (char *t)
{
int i=0,j=0;
Char *m;
for (m=t;t[i]!= '; i++)//m,t represents the first address.
{
j + +;
}
Return J;
}
void Makenext (char *p,int next[])
{
int k=0,q;
int M=len (p);
next[0]=0;
for (k=0,q=1;q<m;q++)
{
while (K>0&&p[k]!=p[q])
K=NEXT[K-1];
if (P[k]==p[q])
{
k++;
}
Else
{
Next[q]=k;
}
}
}
int KMP (char * T,char * p,int next[])
{
int i=0,q=0,k;
int POS;
int Lent=len (t);
int Lenp=len (p);
t[0]=lent;//type inconsistency may be used to cast;
P[0]=LENP;
Makenext (P,next);
for (i=0,q=0;i<lent;i++)
{
while (Q>0&&t[i]!=p[q])
Q=NEXT[Q-1];
if (T[i]==p[q])
{
q++;
}
if (Q==LENP)
{
printf ("Match completion at position N:%d", (i-lenp+1));
}
}
}
int main ()
{
int i=0;
int lent,lenp,pos;
int next[]={0};
Char *text= "Abcababeca";
Char *patten= "Ababe";
printf ("%s\n", text);
printf ("%s\n", Patten);
KMP (Text,patten,next);
return 0;
}
Refer to the Great God's blog------http://www.cnblogs.com/c-cloud/p/3224788.html
kmp//hehe! Look at the pornography algorithm