The editor of the blog Park is too hard to use ...
BF algorithm is the brute force algorithm, very simple, casually lifted a chestnut:
#include <iostream>#include<cstring>using namespacestd;//s[]: to match the chain//t[]: pattern stringintBfsearch (intStartCharS[],Chart[]) { intSlen =strlen (S); intTlen =strlen (T); intI, J; for(i =0; i < Slen-tlen; i++) { for(j =0; J < Tlen; J + +) if(S[i + j]! = T[j]) Break; if(J = =tlen) cout<< i +1<<Endl; }}intMain () {Chars[]="CABABAABCACB"; Chart[]="ABCAC"; Bfsearch (0, S, T); return 0;}
KMP algorithm:
The main implementation content includes a GetNext function and a function to compare strings and patterns;
The implementation of GetNext function is the most important. Principles are described in a number of other articles. Here's where I feel more important.
intnext[ -];Chars[]="CABABAABCACB";Chart[]="ABCAC"; voidGetNext (Chart[]) { intk=-1; intj=0; NEXT[J]=K; while(t[j]!=' /'){ if(k==-1|| t[j]==T[k]) {k++; J++; NEXT[J]=K; } Elsek=NEXT[K]; }}
One of the most important and most essential places in k=next[k];
S[] is a pattern string
NEXT[K] Stores the number of digits with the same k position prefix as the suffix,
Executed when t[j]!=T[k] appears
K = Next[k] Indicates the prefix of the bit (K-bit) before the current position is assigned to K, and
Suffix the same number of digits for the purpose of the next array of next[k] (i.e. p[next[k]])
Full code:
#include <iostream>#include<string.h>using namespacestd;intnext[ -];Chars[]="CABABAABCACB";Chart[]="ABCAC"; voidGetNext (Chart[]) { intk=-1; intj=0; NEXT[J]=K; while(t[j]!=' /'){ if(k==-1|| t[j]==T[k]) {k++; J++; NEXT[J]=K; } Elsek=Next[k]; }}intKmpsearch (CharS[],intStartChart[]) { intSlen =strlen (S); intTlen =strlen (T); intI=start; intj=0; while(I<slen && j<Tlen) { if(j==-1|| s[i]==T[j]) {i++; J++; } ElseJ=Next[j]; } if(t[j]==' /') return(i-j+1); Else return 0;}intMain () {getNext (T); for(intk=0; t[k]!=' /'; k++) cout<<next[k]<<" "; cout<<Endl; cout<<kmpsearch (S),0, T); return 0;}
BF algorithm and KMP algorithm in string pattern matching