題意:找出字串的循環週期
解題思路:
輸入字串的週期,必定是它的因數。
只須找出因數中,最小符合的數N,使前N個字符合字串即可。
#include <iostream>
#include <string>
using namespace std;
int main() {
int n,i,j,k,m,u,ans;
string str,temp;
while(cin>>n){
for(i=1;i<=n;++i){
cin>>str;
for(k=1;k<=str.length();++k){
if(str.length()%k==0){
compare=temp="";
for(j=0;j<k;++j){
temp+=str[j];
}
u=1;
for(j=0;j<str.length();++j){
if(str[j]!=temp[j%k]){
u=0;
break;
}
}
if(u){
ans=k;
break;
}
}
}
if(i==n){
cout<<ans<<endl;
}else{
cout<<ans<<endl<<endl;
}
}
}
return 0;
}
沒有留言:
張貼留言