标签:
abcde a3 aaaaaa aa #
0 3
题意:最多能从文本串中剪出多少个模式串。
因为不能重叠,所以当j匹配的模式串的末尾并且匹配成功时直接把j变成0从新匹配就
好了。
#include <cstring> #include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <cmath> using namespace std; #define maxn 1111 char P[maxn], T[maxn]; int n, m; #define next Next int next[maxn]; void get_next (char *p) { int t; t = next[0] = -1; int j = 0; while (j+1 < m) { if (t < 0 || p[j] == p[t]) {//匹配 j++, t++; next[j] = t; } else //失配 t = next[t]; } } int kmp () { int ans = 0; get_next (P); int i = 0, j = 0; while (i < n && j < m) { if (j < 0 || T[i] == P[j]) { if (j == m-1) { ans++; i++; j = 0; continue; } i++, j++; } else { j = next[j]; } } return ans; } int main () { while (cin >> T) { if (T[0] == '#' && strlen (T) == 1) break; cin >> P; n = strlen (T); m = strlen (P); printf ("%d\n", kmp ()); } return 0; }
标签:
原文地址:http://blog.csdn.net/morejarphone/article/details/51348602