题目链接1
#include<iostream>
using namespace std;
const int N=1000010;
char str[N];
int ne[N];
int n;
int main()
{
int s=0;
while(scanf("%d",&n)==1 && n)
{
scanf("%s",str+1);
ne[1]=0;
for(int i=2,j=0;i<=n;i++)
{
while(j && str[i]!=str[j+1])
j=ne[j];
if(str[i]==str[j+1])
{
j++;
}
ne[i]=j;
}
printf("Test case #%d\n",++s);
for(int i=2;i<=n;i++)
{
int j=ne[i];
if(i%(i-ne[i])==0 && i/(i-ne[i])>=2)
{
printf("%d %d\n",i,i/(i-ne[i]));
}
}
printf("\n");
}
return 0;
}
题目链接二
class Solution {
public:
int strStr(string haystack, string needle) {
const int N=5e4+5;
int ne[N];
int n=needle.size();
if(!n)
return 0;
haystack=" "+haystack;
needle=" "+needle;
for(int i=2,j=0;i<=n;i++)
{
while(j && needle[i]!=needle[j+1])
j=ne[j];
if(needle[i]==needle[j+1])
j++;
ne[i]=j;
}
for(int i=1,j=0;i<=haystack.size();i++)
{
while(j && haystack[i]!=needle[j+1])
j=ne[j];
if(haystack[i]==needle[j+1])
j++;
if(j==n)
return i-n ;
}
return -1;
}
};