分析:
kmp匹配
代码:
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1005;
char s[maxn], p[maxn];
int _next[maxn];
void get_next()
{
int p_len = strlen(p);
int i = 0, j;
_next[0] = j = -1;
while (i < p_len) {
if (j == -1 || p[j] == p[i]) {
i++;
j++;
_next[i] = j;
} else {
j = _next[j];
}
}
}
int get_ans()
{
int s_len = strlen(s);
int p_len = strlen(p);
int ans = 0, i = 0, j = 0;
while (i < s_len) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
} else {
j = _next[j];
}
if (j == p_len) {
ans++;
j = 0;
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
while (cin >> s && s[0] != '#' && cin >> p) {
get_next();
cout << get_ans() << endl;
}
return 0;
}