POJ 2406 Power Strings(KMP)

Power Strings

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
题目大意:求字符串的周期。

解题思路:KMP算法的一部分,只需要求出next数组。对于next[len]与len,有以下几种情况

(1)2 * next[len] < len,这种情况说明中间的一段字符串既不与next[1...j]相等,也不与next[len - j + 1...len]相等,所以周期为1;

(2)2 * next[len] >= len

    ①len % (len - next[len]) == 0,这种情况说明原字符串有周期,周期长度为len - next[len],周期个数为len / (len - next[len]);

    ②len % (len - next[len] != 0,这种情况说明可能存在周期,但是最后一个周期没有完成,所以周期也是1。

代码如下:

#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define EPS 1e-6
#define INF INT_MAX / 10
#define LL long long
#define MOD 100000000
#define PI acos(-1.0)

const int maxn = 1000005;

int next[maxn];
char pattern[maxn];
int len;
void get_next()
{
    memset(next,-1,sizeof(next));
    next[1] = 0;
    for(int i = 2,j = 0;i <= len;i++){
        while(j > 0 && pattern[j + 1] != pattern[i])
            j = next[j];
        if(pattern[j + 1] == pattern[i])
            j += 1;
        next[i] = j;
    }
}

int main()
{
    while(scanf("%s",pattern + 1) != EOF && pattern[1] != '.'){
        len = strlen(pattern + 1);
        get_next();
        int ans = 1;
        if(2 * next[len] >= len && !(len % (len - next[len])))
            ans = len / (len - next[len]);
        printf("%d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值