UVA 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.
题意翻译
如果一个字符串可以由某个长度为kkk 的字符串重复多次得到,则称该串以kkk 为周期。例如,abcabcabcabcabcabcabcabcabcabcabcabc 以333 为周期(注意,它也以666 和121212 为周期)。
输入一个长度不超过808080 的字符串,输出其最小周期。
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
大写的注意
这种题的坑就在于输入输出格式。。。。。说多都是泪哟。。
两个连续的输入将由空白行分隔。
两个连续的输出将由空白行分割。
最后一个输出后面没有空白行。
我的程序运行的输入输出格式是这样的。
JAVA 代码实现
import java.util.Scanner;
public class Periodic_Strings {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = "";
while (n-- != 0) {// 控制输入n组数据
str = sc.next();
int len = str.length();
for(int i=1; i<=len; i++){
if(len%i == 0){
boolean flag = true;
for(int j=i; j<len; j++){
if(str.charAt(j) != str.charAt(j%i)){
flag=false;
break;
}
}
if(flag){ //1、第一条件是i能被len整除;2、当确定能整除后,试探以长度i作为匹配串来匹配,
System.out.println(i);
break;
}
}
}
if(n!=0){
System.out.println();}
}
sc.close();
}
}
注意啦注意啦!!!!!一般OJ系统提交java代码的类名(class),必须是Main。所以大家切记切记啊!!
叨叨
中秋放假3天 ,国庆放假7天,再加前面2天没课,就是连休9天。宿舍4个人,就我一直单身狗。看了报团游凤凰。。一个人有点怕。。。。。悲从中来,宿舍没人,实验室没人,花季少女的我只能屯一堆零食在实验室浪荡啊啊啊啊啊