Each time we find a match, increase the global counter by 1.
For KMP, algorithm, your may refer to the following links which has nice explanations.
- KMP on Jboxer ' s blog;
- KMP on Geeksforgeeks, with a well-commented C code.
1#include <iostream>2#include <string>3#include <vector>4 5 using namespacestd;6 7vector<int> kmpprocess (stringt) {8 intn =t.length ();9vector<int> LPs (N,0);Ten for(inti =1, Len =0; I <N;) { One if(T[i] = =T[len]) Alps[i++] = + +Len; - Else if(len) len = Lps[len-1]; - Elselps[i++] =0; the } - returnLPs; - } - + intKmpstringSstringt) { - intm = s.length (), n = t.length (), CNTs =0; +vector<int> lps =kmpprocess (t); A for(inti =0, j =0; I <m;) { at if(S[i] = =T[j]) { -i++; -J + +; - } - if(j = = N) cnts++; - if(I < m && S[i]! =T[j]) { in if(j) J = lps[j-1]; - Elsei++; to } + } - returnCNTs; the } * $ intMainvoid) {Panax Notoginseng intcases; -scanf"%d", &cases); the for(inti =0; i < cases; i++) { + strings, t; ACIN >>T; theCIN >>s; +printf"%d\n", KMP (S, t)); - } $ return 0; $}
[Hihocoder] KMP algorithm