1. 程式人生 > >UVA455Periodic Strings(最小週期串)

UVA455Periodic 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.

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

//原題連結https://vj.e949.cn/24c0d68c7b969c38f92f9f7f78cb2162?v=1545008735

//這道題的輸入輸出格式是真的一不小心就會錯,全花時間在整格式上了=。=。總之這道題關鍵在於每個週期串長度相同,所以只需要找出最小的讓v1和v2串

//相等的字元個數就行。這道題用string的毛串直接拼接效率會高點,程式碼如下。

#include <iostream>
#include <string>
using namespace std;
int
main() { string v1; int n; cin>>n; while(n--) { int i; cin>>v1; string k=""; for(i=1;i<=v1.size();i++) { k+=v1[i-1]; string v2=""; for(int j=0;j<v1.size()/i;j++) v2+=k; if(v2==v1) break; } cout<<i<<endl; if(n) cout<<endl; } return 0; }