码迷,mamicode.com
首页 > 其他好文 > 详细

KMP入门(周期)

时间:2016-08-06 00:18:31      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Description

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.
 
 
解题思路:题目大意:给定一个字符串由某一个子串重复得来,求出重复的次数。
利用fail数组fail[len],子串循环的次数满足if(len%(len-fail[len])==0)
           ans=len/(len-fail[len]);
否则ans=1
#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

char s[1000005];
int fail[1000005];
int len;

void get_fail();

int main()
{
    while(scanf("%s",s+1),s[1]!=.)
    {
       len=strlen(s+1);
       get_fail();
       int ans=1;
       //ÀûÓÃfail[len]
       if(len%(len-fail[len])==0)
           ans=len/(len-fail[len]);
       printf("%d\n",ans);
    }
}
void get_fail()
{
    memset(fail,0,sizeof(fail));
    fail[0]=-1;
    for(int i=1;i<=len;i++)
    {
        int p=fail[i-1];
        while(p>=0&&s[p+1]!=s[i])
        p=fail[p];
        fail[i]=p+1;
        //cout<<i<<" "<<fail[i]<<endl;
    }
}

 

KMP入门(周期)

标签:

原文地址:http://www.cnblogs.com/hr974041087/p/5742993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!