Periodic Strings UVA - 455

​   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 of 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

HINT

​   这个题目是要求求一个字符串的周期如:521521521的周期就是521的长度3。

​   解题思路就是将整个字符串进行切片处理,分成若干个可能的子字符串逐个判别,这样要解决的问题就有:

​ ​   1.切除来的若干个等长字串如何保证等长?

​ 利用相除取余来判断余数是否为零来解决。

​ ​   2.切出来的等长字串如何来判断其是相等的?

​ ​   将第一个字串作为标准,将其它子串的对应位置的字符进行比较来判断是否满足要求。注意看后面代码如何计算其他字串对应位 置的。

​   注意:输出的格式要求最后一个数字只有一个回车而其他的都有两个回车!!!

Accepted

#include<stdio.h>
#include<string.h>

int main()
{
	int sum;
	scanf("%d", &sum);
	while(sum--)
	{
		char s[85];
		scanf("%s", s);
		int len = strlen(s);
		int flag = 0;
		for (int i = 1;i <= len;i++)				//第一个循环来尝试找出可能的周期
		{
			if (len % i != 0)continue;
			for (int j = 0;j < i;j++)				//第二、第三个循环来按照选定的周期对字符串进行切片判断。
			{
				flag = 0;
				for (int k = 1;k <= len / i;k++)	//len/i切出来的子串的个数
				{
					if (k*i+j<len&&s[j] != s[k * i+j])	//每一次比较一个子串的对应位置的字符是否和第一个字串对应位置处的字符相等。
					{
						flag = 1;
						break;
					}
				}
				if (flag)break;

			}
			if (!flag&&sum!=0)
			{
				printf("%d\n\n", i);
				break;
			}
			else if (!flag && sum == 0)
			{
				printf("%d\n", i);
				break;
			}
		}
		if (flag && sum != 0)				//注意区分最后一个数字的输出格式
			printf("%d\n\n", len);
		else if (flag && sum == 0)
			printf("%d\n", len);

	}
}

posted @ 2021-01-30 20:37  布拉多1024  阅读(46)  评论(0)    收藏  举报