紫书——Periodic Strings UVA - 455

题解:

一开始看下去好难啊,好像数据结构上的kmp串查找,然后发现原来串最大80;好吧又可以枚举了

每次枚举长度为j的串,一旦成功他就是最小的循环串

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
#include <cctype>

using namespace std;


int main() {
	//freopen("in.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	
	int n;
	scanf("%d",&n);
	for(int i = 0; i < n; i++){
		string str;
		cin >> str;
		if(i) printf("\n");
		
		int len = str.size();
		int minlen = 0;
		for(int j = 1;j <= len/2; j++){
			if(len/j != len*1.0/j) continue;	//如果不能平分就直接跳过 
			
			int ci = len/j; 
			string sym = str.substr(0,j); //假设目标串 
			int pos = j;	//匹配串的开始位置 
			int k;
			for(k = 1; k < ci; k++){
				string tmp = str.substr(pos,j);
				if(tmp.compare(sym) != 0) break;
				pos += j; 
			}
			
			if(k == ci){
				minlen = j; break;
			}
		}
		
		if(!minlen) minlen = len;
		printf("%d\n",minlen);
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/a673953508/article/details/80111722