//
// main.cpp
// KMP
//
// Created by liuzhe on 16/7/16.
// Copyright © 2016年 my_code. All rights reserved.
//
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;
/*char t[1000010],w[10010];
int _next[10010];
void get_next(int len)
{
_next[0]=-1;
int i=0,j=-1;
while(i<len)
{
if(j==-1||w[i]==w[j])
_next[++i]==++j;
else
j=_next[j];
}
}
int KMP()
{
int len1=strlen(t),len2=strlen(w);
get_next(len2);
int i=0,j=0;
int ans=0;
while(i<len1)
{
if(j==-1||t[i]==w[j])
i++,j++;
else
j=_next[j];
if(j==len2)
ans++,j=_next[j];
}
return ans;
}
int main(int argc, const char * argv[]) {
// insert code here..
//cin>>w>>t;
while(scanf("%s%s",w,t)!=-1)
{ if(w[0]=='#')
break;
else
{int ans=KMP();
//cout<<q<<endl;}
printf("%d\n",ans);
}
}
//std::cout << "Hello, World!\n";
return 0;
}*/
char a[1000000],b[1000000];
int p[1000000],n,m,ans;
void fail()
{
int i,j=-1;
p[0]=-1;
for(i=1;i<m;i++)
{
while(j>=0&&b[j+1]!=b[i]) j=p[j];
if(b[i]==b[j+1]) j++;
p[i]=j;
}
}
int kmp()
{
int i,j=-1;
ans=0;
for(i=0;i<n;i++)
{
while(j>=0&&b[j+1]!=a[i]) j=p[j];
if(a[i]==b[j+1]) j++;
if(j==m-1)
{
ans++;
j=-1;
}
}
return ans;
}
int main()
{
while(scanf("%s",a)!=EOF)
{
if(a[0]=='#'&&strlen(a)==1)
break;
else
{
scanf("%s",b);
n=strlen(a);
m=strlen(b);
fail();
printf("%d\n",kmp());
}
}
return 0;
}
hdu 2087
最新推荐文章于 2020-09-26 13:30:01 发布