poj_2406 KMP寻找重复子串问题

B - Power Strings
Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit  Status

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.

 

 又是纯KMP算法
昨晚太晚了,浏览了下题目,就好困,然后就睡觉去了
今天早上坐公交的时候开始想了下这个题目,就想出来做法了。(PS.长沙周一上班高峰,公交真TM挤。地铁遥遥无期啊)。
做法如下:
只需用KMP算法求出next数组值,这个具体求法我昨晚的日志写的很清晰。
在求的过程中,用一个变量记录最新的失配处的位置,这样,初始点到失配点的字符串,即为重复母串,比如ababab,从第三位到最后一位均可匹配,因此失配点即为第二位,b。。因此结果就是总位数6/2=3;
当然之前想简单了,比如abababa,如果按上述做法,也会输出3.因为它的next值为0012345,明显失配处好像是第二位。。。实则要加入判断条件:如果总位数%重复母船长度!=0,则重复母串不存在,直接输出1.
 
#include <iostream>
#include <cstdio>
using namespace std;
char str[1000005];
int next[1000005];
int knext()
{
    int mini=0;
    next[0]=0;
    int i,j=0;
    for (i=1;str[i]!='\0';i++)
    {
        if (str[i]==str[j]) j++;
        else
{ while (j>0&&str[j]!=str[i]) j=next[j-1];
if (str[j]==str[i]) j++;
} next[i]
=j; if (next[i]!=next[i-1]) mini=i-j;//当前失配,记录最新失配点。 } if (i%(mini+1)==0)//如果重复母串根本不能构成总串,说明根本不是重复母串。 return i/(mini+1); else return 1; } int main() { while (gets(str)) { if (str[0]=='.') break; printf("%d\n",knext()); } return 0; }

 

转载于:https://www.cnblogs.com/kkrisen/p/3237674.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值