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

题意

给你一个字符串,找出他最多是重复了几次。比如aaaa就是以a重复了4次,abab就是以ab重复了2次

解题思路

首先找到周期,然后再判断重复了几次。

找周期的时候引用两个下标 i,j 。i-j表示周期的长度,j表示上一个周期内某个元素,i表示这个元素对应的下一个周期中的元素。

i初始为0,j初始为-1。

例如

字符串a为 ababa

数组b存的是每个字符的重复次数,初始为零,最终答案就是最后一个字符重复次数加1即可

01234
ababa

当i=1指向b,j=0指向a时,二者不相等 ----->(说明周期找的不对,重新找) j重新指向头,i后移一个单位

此时i=2指向a,j=0指向a,二者相等 ------>b[i]=b[j]+1]=1   i,j分别后移一个单位,周期为2

此时i=3指向b,j=1指向b,二者相等 ------>b[i]=b[j]+1] =1  i,j分别后移一个单位,周期为2

此时i=4指向a,j=2指向a,二者相等------>b[i]=b[j]+1] =2   i,j分别后移一个单位,周期为2

此时i=5指向结束符,j=3指向b,二者不相等 并且字符长度为5不能整除周期2 ----->b[ 0~i ] =0,(循环次数清零)

代码

#include <cstring>
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#define INF 0x3f3f3f3f
const int maxn=50100;
using namespace std;
char s[1000000];
int  b[1000000];
int main()
{
    while(scanf("%s",s) && s[0]!='.')
    {
        memset(b,0,sizeof(b));
        int j=-1,i=0;
        int len=strlen(s);
        while(i<len)
        {
            i++;j++;

            if(s[i]==s[j])
            {
                b[i]=b[j]+1;
            }
            else//周期不对就重新找
            {
                if(i>=len)
                    if(len%(i-j)==0)
                        break;

                j=-1;
             for(int k=0;k<=i;++k)
                b[k]=0;
            }
        }
        printf("%d\n",b[len-1]+1);
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值