样例输入:HoHoHo
样例输出:2
特别注意这种输入情况:HoHHoHHoH
java代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class strPeriodic {
/**
* @param args
*/
private static int t=0;
public static void main(String[] args) throws Exception{
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
char[] arr = str.toCharArray();
if(arr.length>80){
System.out.println("Input Error");
return;
}
int k=0;
for(int i=1;i<arr.length;i++){
if(arr[i]==arr[k]){
t=i-k;//t为周期
String sstr = str;
while(t<sstr.length()){
String s1 = str.substring(0,t);
if(!s1.equals(sstr.substring(0,t))){
break;
}
sstr = sstr.substring(t, sstr.length());
}
if(t==sstr.length()){
System.out.println(t);
break;
}
}//if
}//for
}
}
c语言代码:
#include<stdio.h>
#include<string.h>
int main(){
char word[100];
scanf("%s",word);
int len = strlen(word);
for(int i=1;i<=len;i++){
if(len%i==0){
int ok = 1;
for(int j=i;j<len;j++){
if(word[j]!=word[j%i]){
ok = 0;
break;
}//if
}//for
if(ok){
printf("%d\n",i);
break;
}
}//if
}//for
return 0;
}