贪心分析下,尽可能选考前面的匹配,每次从上个匹配的位子开始kmp
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
using namespace std;
//typedef long long lld;
const int oo=0x3f3f3f3f;
//const lld OO=1LL<<61;
const int MOD=(1e9)+7;
const int maxn=1005;
int next[maxn];
char s1[maxn],s2[maxn];
void get_next(int len)
{
int i=0;next[i]=-1;
int j=-1;
while(i<len-1)
{
if(j==-1||s2[i]==s2[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
int kmp(int pos,int len1,int len2)
{
int i=pos;
int j=0;
while(i<len1&&j<len2)
{
if(j==-1||s1[i]==s2[j])
{
i++;
j++;
}
else
j=next[j];
}
if(j>=len2)
return i;
else
return -1;
}
int main()
{
while(scanf("%s",s1)!=EOF)
{
if(s1[0]=='#')break;
scanf("%s",s2);
int len1=strlen(s1);
int len2=strlen(s2);
get_next(len2);
int pos=0,ans=0;
for(int i=0;i<len1;i++)
{
pos=kmp(pos,len1,len2);
if(pos!=-1)
ans++;
else break;
}
printf("%d\n",ans);
}
return 0;
}
/**
abcd
-> abcdabc
abcda
*/