不多说 模板自己怎麽顺手怎末写 纯粹是为了整理 方便复习 不了解的推荐一个博客 http://www.cnblogs.com/c-cloud/p/3224788.html 应该是目前讲的比较详细的一个;
#include <iostream>
#include <string.h>
using namespace std;
int ans,next[2010];
char s1[2010],s2[2012];
void get_next(char *str) //求匹配表 也就是next数组
{
int k,q,len;
len=strlen(str);
next[0]=0;
for (k=0,q=1;q<len;q++)
{
while (k>0&&str[k]!=str[q])
k=next[k-1];
if (str[k]==str[q])
k++;
next[q]=k;
}
}
void kmp(char *s1,char *s2) //求次数
{
int len1,len2,q=0;
len1=strlen(s1);
len2=strlen(s2);
get_next(s2);
for (int i=0;i<len1;i++)
{
while (q>0&&s1[i]!=s2[q])
q=next[q-1]; //更新q位置相当于后移
if (s1[i]==s2[q])
q++;
if (q==len2)
ans++;
}
}
int main()
{
scanf ("%s%s",s1,s2); //ans 忘了赋值0 ,要先吧ans赋值为零。
kmp(s1,s2);
cout<<ans<<endl; //出现次数
return 0;
}