Looking at the approximate steps of the algorithm, and then each one to prove the correctness of each step, the comments write some understanding.
This is not a fresh approach, just feel that the program is very delicate, repeated use of mathematical induction method.
It makes me feel fresh.
1 /*2 Next[i] Storage: match[i] mismatch, orig in the corresponding position will match the value3 According to KMP's thought,4 That is, the prefix of the longest and the same suffix in the 1 to i-1 substring the last item5 and this one is different from match[i]6 7 if no prefix string exists but the first item differs from the I key, the value is 1. 8 If there is no prefix string and the first item is the same as I, the value is 0 and the J moves backward one position. 9 */Ten#include <stdio.h> One intMainvoid) A { - Charorig[ -],match[ -]; - intnexterval[ -],next[ -],lengthorig,lengthmatch; the for(lengthorig=1;; lengthorig++){ - Charch; -scanf"%c",&ch); - if(ch=='\ n'|| ch==' '){ +lengthorig--; - Break; + } Aorig[lengthorig]=ch; at } - for(lengthmatch=1;; lengthmatch++){ - Charch; -scanf"%c",&ch); - if(ch=='\ n'|| ch==' '){ -lengthmatch--; in Break; - } tomatch[lengthmatch]=ch; + } -next[1]=0; thenext[2]=1; * for(intI=3; i<=lengthmatch+1; i++) {//Next store the object that will match if I bit does not match $ intk=i-1;//that is, the last number of the longest prefix in 1 to i-1Panax Notoginseng while(1){ - if(k==1){ thenext[i]=1; + Break; A } the if(match[i-1]==Match[next[k]]) { +next[i]=next[k]+1; - Break; $ } $K=NEXT[K];//If you cannot prolong the formation of a substring next[k]+1 -}//and there is a substring of M, that substring must be a substring of the previous substring - } the for(intI=2; i<=lengthmatch+1; i++) {//if I!=0,match[next[i]] and match[i] must be different - if(Match[i]==match[next[i]])//if Match[i]==match[next[i]]WuyiNext[i]=next[next[i]];//already have match[next[i]]!=match[next[next[i] ] the}//must have match[i]!=match[next[next[i] ] - intI=1, j=1, total=0; Wu while(1){//The item in front of I at the end of the while is already matched to the J front, and all previous matches have been tried - if(i==lengthmatch+1){ About++Total ; $I=Next[i]; - Continue; -}//i-1 a successful match at the head - if(j==lengthorig+1) Break; A //when J-1 has i-1 to the end, the length limit of orig cannot match. + if(i==0){ the++j,++i; - Continue; $}//The first item does not match up with the back consideration of one the if(Match[i]==orig[j]) ++i,++J; the ElseI=Next[i]; the } theprintf"They is match for%d times.", total); -}
Improved KMP pattern matching algorithm