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

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

Output An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.code

Sample Inputorm

1
HoHoHo blog

Sample Output ci

2get

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

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

//相等的字符個數就行。這道題用string的毛串直接拼接效率會高點,代碼以下。it

#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;
}
相關文章
相關標籤/搜索