Let's look at a topic: Hihocoder #1015: KMP algorithm
Input
The first line, an integer n, represents the number of test data groups.
The next n*2 line, each of the two lines represents a test data. In each test data, the first behavior pattern string consists of no more than 10^4 uppercase letters, the second behavior of the original string, consisting of no more than 10^6 uppercase letters.
where n<=20
Output
For each test data, output a line of ans in the order in which they appear in the input, indicating the number of times the pattern string appears in the original string.
Sample input
5
HA
hahaha
Wqn
Wqn
Ada
Adadada
Bababb
Bababababababababb
DAD
Addaadaaddaaadaad
Sample output
3
1
3
1
0
The implementation code is as follows:
#include <iostream>#include<string>using namespacestd;intSum//used to record the number of times such substrings have occurredintGetNext (stringTint*next);voidKmpmatch (stringSstringt);intMain () {stringS,t;//t mode string, s original string intN; CIN>>N; while(n--) {cin>>t>>s; Sum=0; Kmpmatch (s,t); cout<<sum<<Endl; }}intGetNext (stringTint*next) {next[0]=-1; intI=0, j=-1; while(I<t.length ()-1){ if(j==-1|| t[i]==T[j]) {i++; J++; Next[i]=J; } ElseJ=Next[j]; }}voidKmpmatch (stringSstringt) { intnext[100000],i=0, j=0; GetNext (T,next); while(i<s.length ()) { if(j==-1|| s[i]==T[j]) {i++; J++; } ElseJ=Next[j]; if(j==t.length ()) {Sum++; J--; I--; J=NEXT[J];//prevent missing, such as: Adadada,ada appeared three times } }}
Once each complete match succeeds, let J=next[j], why do we know by an example.
Suppose there is an original string s:cabababdba, pattern string t:abab, now to find the number of times the pattern string T appears in the original string s.
KMP: The magical of Next array