题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
abcde a3 aaaaaa aa #
0 3
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cstdio>
#include <cmath>
using namespace std;
char s[1100],t[1100];
int next[1100];
void get_next() //获取next[]
{
int i=1,j=0;
int len=strlen(t);
next[1]=0;
while(i<len)
{
if(j==0||s[i]==t[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}
}
int kmp()
{
int sum=0;
int i=1,j=1;
int len1=strlen(s);
int len2=strlen(t);
while(i<=len1)
{
if(j==0||s[i-1]==t[j-1])
{
i++;
j++;
}
else
j=next[j];
if(j>len2)
{
sum++;
j=1;
}
}
return sum;
}
int main()
{
while(scanf("%s",s)!=EOF)
{
if(s[0]=='#')break;
scanf("%s",t);
get_next();
printf("%d\n",kmp());
}
return 0;
}
原文地址:http://blog.csdn.net/liusuangeng/article/details/39183983