The man was too foolish to look at the kmp of the day.
Just started to see the training guide, and later surprised to find that the original Rujia write F array is not the next array!
I always feel different from what I've seen before ...
Then Baidu a bit KMP, studied for a long time, and then wrote a copy of their own logic
Http://blog.chinaunix.net/uid-23767307-id-5033555.html
The man KMP The big space, and we can see it.
Personally, it is not very difficult to write the KMP algorithm as long as you can understand the meaning of the next array.
However, their language is not good enough to explain, and directly paste my template.
#include <map> #include <set> #include <cmath> #include <stack> #include <queue> #include <cstdio> #include <string> #include <vector> #include <cstring> #include <iostream># Include<algorithm> #include <functional>using namespace std;const int MX = 1e6 + 5;char s1[mx], S2[mx];int Next [Mx];int KMP (Char *a, char *b) {int m = strlen (A), n = strlen (B); Next[0] = 0; for (int i = 1; i < n; i++) {int k = next[i-1]; while (b[i]! = b[k] && k) k = next[k-1]; Next[i] = b[i] = = B[k]? K + 1:0; } int ans = 0, j = 0; for (int i = 0; i < m; i++) {while (a[i]! = B[j] && j) j = Next[j-1]; if (a[i] = = B[j]) j + +; if (j = = n) ans++; } return ans; int main () {int T, Ansk = 0; Freopen ("Input.txt", "R", stdin); scanf ("%d", &t); while (t--) {scanf ("%s%s", S1, S2); printf ("%d\n", KMP (S2, S1)); } return 0;}Where, if you want the function to return the number of occurrences, not the number of matches
Because there will be some overlap in the number of matches, just change one place.
Put if (j = = n) ans++; change to if (j = = N) ans++, j = 0; it's all right.
int KMP (char *a, char *b) {//a is the searched string, B is the content of the search, and returns the number of occurrences of B in a, int m = strlen (A), n = strlen (B); Next[0] = 0; for (int i = 1; i < n; i++) { int k = next[i-1]; while (b[i]! = b[k] && k) k = next[k-1]; Next[i] = b[i] = = B[k]? K + 1:0; } int ans = 0, j = 0; for (int i = 0; i < m; i++) {while (a[i]! = B[j] && j) j = next[j-1]; if (a[i] = = B[j]) j + +; if (j = = N) ans++, j = 0; } return ans;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
KMP hihoCoder1015 KMP algorithm