Purple Book, Exercise 3-4 Find the Minimum Period of a String




/*
	Ideas:
	for the string s
	Compares all characters preceding s starting from the second character of s
	The condition for comparison is that the number of characters in front of s must be a divisor of len
	That is to say, len%i == 0 can be compared (the length of the following characters must be a multiple of the front, your code does not add this condition)
	 
	Please see the code comments for details
*/


#include<cstdio>
#include<cstring>
char s[100];
intmain()
{
	int t;
	scanf("%d",&t);//Number of test samples
	while(t--)
	{
		memset(s,0,sizeof(s));//initialize s
		scanf("%s",s);//input string s
		int len=strlen(s);//Length of s
		int flag;//A flag to determine whether to jump out of the loop
		for(int i=1;i<=len;i++)//From here we have to write i<=len because if the period of this string may be its length
			if(len%i==0)//If the number behind is a multiple of i, then compare (len-i)%i==0 ---> len%i==0
			{
				flag=1;
				for(int j=i;j<len;j++)//Start from i to judge whether the string with length i is the same in front
					if(s[j]!=s[j%i])
					{
						flag=0;//There are different proofs that the first i character is not the number of cycles
						break;//Exit the loop, continue to judge
					}
				if(flag)	
				{
					printf("%d\n",i);//If it is the number of cycles, input i .....you have to write \n here, it will be WA without writing
					break;//Exit after finding
				}
			}
		if(t) printf("\n");//When t is not 0, output a blank line
	}
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325743956&siteId=291194637