455 – Periodic Strings
A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. For example, the string “abcabcabcabc” has period 3, since it is formed by 4 repetitions of the string “abc”. It also has periods 6 (two repetitions of “abcabc”) and 12 (one repetition of “abcabcabcabc”).
Write a program to read a character string and determine its smallest period.
Input
The first line oif the input file will contain a single integer N indicating how many test case that your program will test followed by a blank line. Each test case will contain a single character string of up to 80 non-blank characters. Two consecutive input will separated by a blank line.
Output
An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.
Sample Input
1
HoHoHo
Sample Output
2
曾经做过这种通过next数组求循环节的问题,方法还是这样:
1.求出next数组,字符串的长度为len
2.循环节的长度cyclic=len-next[len]
3.如果next[len]==0或者len%cyclic!=0,即循环节的个数不是整数个,那么循环节长度就是len
有一个很重要的就是最后一个回车不要出输出,否则会WA,因为这个错了n次,以往会有PE提醒,这也告诉我们要严格按照题目的要求输出。
#include <iostream>
#include <stdio.h>
#include <string.h>
#define MAX 100
using namespace std;
int next[MAX];
char str[MAX];
int len;
void get_next()
{
int j,k;
j=0,k=-1;
next[0]=-1;
while(j<len)
{
if(k==-1||str[j]==str[k])
{
j++,k++;
next[j]=k;
}
else
k=next[k];
}
if(next[len]==-1)
next[len]=0;
}
void show()
{
for(int i=0;i<=len;i++)
{
printf("%d ",next[i]);
}
printf("\n");
}
int main()
{
int n,cyclic;
scanf("%d",&n);
getchar();
while(n--)
{
scanf("%s",str);
len=strlen(str);
get_next();
cyclic=len-next[len];
show();
if(next[len]==0||len%cyclic!=0)
printf("%d\n",len);
else
printf("%d\n",cyclic);
if(n)
printf("\n");
}
return 0;
}