uva455
如果想要判断一个子字符串是否是最小周期的那个字符串,必须要全部遍历一遍才会知道;
所以可以用字符串的首尾相连,即(i+j)%n,一个一个判断;
另一个思路是,可以先截取字符串前n个,将这前n个加到截取剩下的字符串末尾,然后与原串比较是否相同,如果相同,则说明这个字符串的长度就是最小周期;(substr函数)
#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[100];
int N;
cin >> N;
while (N--)
{
cin >> str;
int len = strlen(str), t = 1;
while (1)
{
int c = 0;//
for (int i = 0; i < len; ++i)
if (str[i] == str[(i + t) % len]) c++;//如果字符串有一个匹配的,那么就延续到下一个,知道n个都匹配;
else break;
if (c == len) break;//只要不是n个都匹配,那么周期就不是它;
t++;
}
cout << t << endl;
if (N != 0) cout << endl;
}
return 0;
}
#include<bits/stdc++.h >
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string a;
cin>>a;
int period=1;
int n=a.length();
while(1)
{
int flags=0;
for(int i=0; i<n; i++)
{
if(a[i]!=a[(i+period)%n])
{
flags=1;
period++;
break;
}
}
if(flags==0){//flags用来做标志;
cout<<period<<endl;
break;
}
}
}
}
但其实,因为是周期性的,所以,周期字符串的长度一定会是n的倍数,这样的话会减少一定的时间;