您的位置:首页 > 其它

HDU - 2087 剪花布条——kmp

2017-08-21 13:40 441 查看
模板题

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1000 + 10;
char s[maxn], p[maxn];
int lens, lenp, Next[maxn];
void makeNext() {
int pos = 0, len = 0;
Next[pos] = len;
for (pos = 1; pos < lenp; pos++) {
while (len && p[pos] != p[len]) len = Next[len - 1];
if (p[pos] == p[len]) len++;
Next[pos] = len;
}
}
int kmp() {
int ans = 0;
makeNext();
for (int i = 0, j = 0; i < lens; i++) {
while (j && s[i] != p[j]) j = Next[j - 1];
if (s[i] == p[j]) j++;
if (j == lenp) {
ans++;
j = 0;
}
}
return ans;
}
int main() {
while (~scanf("%s", s) && s[0] != '#') {
scanf("%s", p);
lens = strlen(s), lenp = strlen(p);
printf("%d\n", kmp());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: