kmp算法

Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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

给一个字符串,找到循环节的数目。
前缀"指除了最后一个字符以外,一个字符串的全部头部组合;

"后缀"指除了第一个字符以外,一个字符串的全部尾部组合。

这里举个例子:
在这里插入图片描述

在这里插入图片描述
这样我们就求出来了next数组

我们求next[3]的时候,已经求出next[0]~next[2],此时我们知道了next[2]=1,意味着next[2]是代表着字符串的前缀与后缀相同的最大长度为1。

也就是对于ABA来说,前缀与后缀相同的最大长度为1,这是我们已知的条件,现在我们要知道对于ABAB来说,前缀与后缀相同的最大长度为??????

对于ABA来说,前缀"AB",后缀"BA",对于ABAB来说,前缀“ABA”,后缀“BAB”,现在我们观察得出结论

ABAB的前缀和后缀必然分别包含ABA的前缀和后缀,即next[3]字符串的前缀和后缀必然分别包含next[2]的前缀和后缀,

无论该字符串是何值。

既然我们已经知道了next[2]=1,代表着ABA的前缀与后缀相同的最大长度为1,那我们计算next[3]的时候,就知道了第一个字符必然是相同的,所以我们无需再比较第一个字符了,(KMP算法就是为了省这一步!!!!),所以我们将t[3]直接与t[1]而不是t[0]比较,若t[3]=t[1],那我们可以直接说next[3]=2=next[1]+1.

  #include <stdio.h>
 #include <string.h>
 #include <algorithm>
 using namespace std; 
long long l,nx[1000000];

  void wsx(char s[])
 {
int i=0,j=-1;
nx[0]=-1;
while(i<l)
{
	if(j==-1||s[i]==s[j])
	{
		i++;
		j++;
		nx[i]=j;
	}
	else
	j=nx[j];
}
}
 char ss[1001000];
    int main()
 {
while(~scanf("%s",ss))
{
    if(ss[0]=='.')
    break;
    l=strlen(ss);
    wsx(ss);
    int t=l-nx[l];
    if(l%t==0)如果第i-1位为结尾的循环必定有 i % (i - Next[i]) == 0
    printf("%d\n",l/t);
    else
    printf("1\n");
    
}
return 0;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值