next数组

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

Output

For each s you should print the largest n such that s = a^n for some string a.

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

就是问你一个串的前缀和另一个串的后缀最大匹配长度是多少

思路就是把两个字符串加到一块形成一个新字符串,然后利用next数组的性质,取n=next[n1+n2]

注意判断n要是大于n1,n2的情况,n不能大于他们

#include 
#include 
#include 
using namespace std;
string str;
string str1;
int Next[2000001];
int rec[2000001];
int n,n1;
void get_Next()
{
    int i=0,j=-1;
    Next[0]=-1;
    while(str[i])
    {
        if(j==-1 || str[i]==str[j])
            Next[++i]=++j;
        else
            j=Next[j];
    }
}
int main()
{
    int t,i,j;
    int ans=0;
    while(cin>>str)
    {
        //printf("Test case #%d\n",++ans);
        cin>>str1;
        int l1=str.size();
        int l2=str1.size();
        n=str.size()+str1.size();
        str=str+str1;
        //str[n]='a';//Next[0]是-1,可看做补0的空缺。
        get_Next();
        int r1=Next[n];
        if(r1!=0)
        {
            if(r1>=l1)r1=l1;
            if(r1>=l2)r1=l2;
            for(int i=0; i

 

你可能感兴趣的:(ACM,KMP)