首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

poj3641(KMP求子串反复次数)

2012-09-10 
poj3641(KMP求子串重复次数)题目链接:http://poj.org/problem?id3461题意:求字符串T在字符串W中出现的次

poj3641(KMP求子串重复次数)

         题目链接:http://poj.org/problem?id=3461

         题意:求字符串T在字符串W中出现的次数。

代码:

#include<stdio.h>#include<string.h>char W[100005];int next[100005];char T[1000005];int ans ;int lenW,lenT;void getnext(){int i,j;next[1]=0;    j=0;for(i=2;i<=lenW;i++){ while(j>0 && (W[j+1] - W[i] !=0) )  j=next[j];         if(W[j+1] == W[i])  j=j+1;         next[i]=j;}}void getans(){int i,j;j=0;ans = 0;    for(i=1;i<=lenT;i++)    {     while(j>0 && (W[j+1] != T[i]) ) j=next[j];     if(W[j+1] == T[i]) j=j+1;     if(j == lenW)     {ans++;j=next[j]; }}}int main(){int ncase;scanf("%d",&ncase);getchar();while(ncase--){memset(W,'\0',sizeof(W));memset(T,'\0',sizeof(T));        gets(W+1);gets(T+1);lenW = strlen(W+1);lenT = strlen(T+1);getnext();getans();printf("%d\n",ans);}return 0;}


 

热点排行