题目链接:剪花布条 题目大意:给你一个模式串和原串,问能从原串中剪出多少个模式串来 题目思路:KMP,只不过在i的遍历时需要将他提到匹配后j的后一个字符去,这样就不
题目链接:剪花布条
题目大意:给你一个模式串和原串,问能从原串中剪出多少个模式串来
题目思路:KMP,只不过在i的遍历时需要将他提到匹配后j的后一个字符去,这样就不会出现被剪过的字符再次匹配的情况
#include <bits/stdc++.h>using namespace std;
const int maxn = 1e6+10;
char str[maxn],mo[maxn];
int Next[maxn];
void getNext(){
int i = 0,j = -1,len = strlen(mo);
while(i < len){
if(j == -1||mo[i] == mo[j]) Next[++i] = ++j;
else j = Next[j];
}
}
int kmp(){
int i = 0,j = 0,l1 = strlen(str),l2 = strlen(mo);
int ans = 0;
while(i < l1){
if(j == -1||mo[j] == str[i])
i++,j++;
else j = Next[j];
if(j == l2){
ans++;
i = i+j-1;
}
}
return ans;
}
int main(){
while(~scanf("%s",str)){
if(str[0] == '#') break;
scanf("%s",mo);
Next[0] = -1;
getNext();
printf("%d\n",kmp());
}
return 0;
}