1686 - 78ms:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1000000+5;
long NEXT[MAXN];
char str1[MAXN],str2[MAXN];
void getNext()
{
int i,j;
NEXT[0]=-1;
for( i=1,j=-1; str1[i]!='\0'; i++ )
{
while( j!=-1 && str1[i]!=str1[j+1] ) j=NEXT[j];
if( str1[i]==str1[j+1] ) j++;
NEXT[i]=j;
}
}
int kmp()
{
int i,j;
int sum=0;
for( i=0,j=-1; str2[i]!='\0'; i++ )
{
while( j!=-1 && str1[j+1]!=str2[i] )j=NEXT[j];
if( str1[j+1]==str2[i] ) j++;
if( str1[j+1]=='\0' )//在原串中匹配str1完毕
{
sum++;
j=NEXT[j];//j值回溯
}
}
return sum;
}
int main()
{
int t;
scanf("%d",&t);
getchar();
while(t--)
{
gets(str1);
gets(str2);
getNext();
printf("%d",kmp());
puts("");
}
return 0;
}
2087 - 0ms:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1000000+5;
long NEXT[MAXN];
char str1[MAXN],str2[MAXN];
void getNext()
{
int i,j;
NEXT[0] = -1;
for( i = 1, j = -1; str1[i]!='\0'; ++i)
{
while( j!=-1 && str1[i] != str1[j+1]) j= NEXT[j];
if( str1[i] == str1[j+1] )++j;
NEXT[i] = j;
}
}
int kmp()
{
int i,j;
int sum = 0 ;
for( i = 0, j = -1; str2[i]!='\0'; ++i)
{
while( j!=-1 && str1[j+1]!=str2[i])j = NEXT[j];
if( str1[j+1] == str2[i] )++j;
if( str1[j+1] =='\0')
{
++sum;
j = -1; // 花条不能重叠 直接将 j 值回到 -1 从头开始匹配
}
}
return sum;
}
int main()
{
while( scanf("%s",str2) && str2[0] !='#' )
{
scanf("%s",str1);
getNext();
printf("%d",kmp());
puts("");
}
return 0;
}
3746 - 109ms
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN = 100000+5;
char str[MAXN];
int NEXT[MAXN];
void getNEXT()
{
int i,j;
NEXT[0] = -1;
for( i = 1 , j = -1 ; str[i]!='\0';++i )
{
while( j!= -1 && str[i]!= str[j+1])j = NEXT[j];
if( str[i] == str[j+1] ) ++j;
NEXT[i] = j;
}
}
int main()
{
int t;
scanf("%d%*c",&t);
while( t-- )
{
gets(str);
getNEXT();
int len = strlen(str);
int ring = len - NEXT[len-1] - 1;
if( len%ring || ring == len )
printf("%d\n",ring-len%ring);
else puts("0");
}
return 0;
}