To find the minimum period of a string

Source: Internet
Author: User

If a string is repeated multiple times with a string of length k, we say that the string is in the period of K, for example: Abcabcabcabc with a period of 3, (note that it also takes 6 and 12 as periods), enter a string of not more than 80 in length, and output a minimum period.

The idea is to enumerate the cycles from small to large, and meet the criteria to jump out.

#include <cstdio>
#include <cstring>

int main ()
{
    //freopen ("A.txt", "R", stdin);
    Char s[100];
    int flag;
    while (scanf ("%s", s)!=eof)
    {
        int len=strlen (s);
        for (int i=1;i<len;i++)
        {
            if (len%i==0)  //Enumeration I is period
            {
                flag=1;
                for (int j=i;j<len;j++)//Compare whether the current character is equal to the corresponding character in the first period,
                {
                    if (s[j]!=s[j%i]) {flag=0;break;}}
            }
            if (flag) {printf ("%d\n", I); break;}
        }
    }
	return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.