Original question:
A character string is said to having period K if it can be formed by concatenating one or more repetitions of another string of length K. For example, the string "ABCABCABCABC" had period 3, since it was formed by 4 repetitions of the string "abc". It also has periods 6 (both repetitions of "ABCABC") and (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 would contain a single integer N indicating what many test case which your program would TES T followed by a blank line. Each of the test case would contain a single character string of Non-blank characters. Consecutive input would separated by a blank line.
Output
An integer denoting the smallest period of the input string for each input. The consecutive output is separated by a blank line.
Sample Input
1
Hohoho
Sample Output
2
English
Give you a string that lets you find the smallest cycle
#include <bits/stdc++.h>
using namespace std;
const int maxnum=1000000;
int Next[maxnum];
Char P[maxnum];
int Plen;
void GetNext (char* p,int plen)
{
Next[0] =-1;
int k =-1;
int j = 0;
while (J < Plen)
{
if (k = =-1 | | p[j] = = P[k])
{
++k;
++j;
NEXT[J] = k;
}
else
{
k = next[k];
}}} int main ()
{
Ios::sync_with_stdio (false);
int t;
cin>>t;
while (t--)
{
cin>>p;
int ans;
Plen=strlen (p);
GetNext (P,plen);
ans=0;
if (plen% (Plen-next[plen));
cout<<plen<<endl;
else
{
ans= (Plen-next[plen]);//plen-next[plen] is to find the length of a looping section
cout<<ans<<endl;
}
if (t)
cout<<endl;
}
return 0;
}
idea:
found a simple string on the purple book to practice practiced hand, and found that KMP can solve ~ using the KMP algorithm prefix array to find the smallest loop section
The total length of the string is Plen
period is plen-next[ Lpen]
First judge is not a periodic string plen% (Plen-next[plen]), if divisible by the period string, otherwise is a non-periodic string, output the original length can be