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);

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就很好(*^_^*)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值