欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

周期串 Periodic Counting, UVa455

程序员文章站 2024-03-19 19:09:52
...

周期串 Periodic Counting, UVa455

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t-- > 0)
	{
		string str;
		cin >> str;
		const int len = str.length();
		int period = len;
		for (int i = 1; i <= (len + 1) / 2; ++i)
		{
			if (len % i != 0)
				continue;
			string sub(str, 0, i);//将sub初始化为从str[0]到str[i-1]的字符串
			int count = 1;
			int current = i;
			while (current < len)
			{
				if ((current = str.find(sub, current))== string::npos)
					break;
				else
				{
					++count;
					current += i;
				}
			}
			if (count == len / i)
			{
				period = i;
				break;
			}
		}
		if (t != 0)
		{
			cout << period << endl << endl;
		}
		else
			cout << period << endl;
	}
}

注:最后一组数据不应输出空行,否则会PA

相关标签: 算法入门紫