POJ - 2406 Power Strings

https://vjudge.net/problem/POJ-2406

POJ - 2406 Power Strings

题目

在这里插入图片描述

分析

在这里插入图片描述
暴力搜索也能过

KMP代码

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int N=1e6+10;
int ne[N];
string s;
int main()
{
	while(cin>>s)
	{
		if(s==".") break;
		
		int n=s.size();
		ne[0]=-1;
		for(int i=0,j=-1;i<=n;)
		{
			if(j==-1 || s[i]==s[j])
			{
				i++,j++;
				ne[i]=j;
			}
			else
				j=ne[j];
		}
		
		int tp=n-ne[n];
		if(n%tp==0)
			printf("%d\n",n/tp);
		else
			printf("1\n");	
	}
	return 0;
}

暴力搜索

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1000000+10;
int ls;
char s[N];
bool check(int x)
{
	int lx=0;
	string a,b;
	for(int i=1;i<=x;i++) a+=s[i];
	
	for(int i=x+1;i<=ls;i++)
	{
		b+=s[i];
		lx++;
		if(x==lx)
		{
			if(a!=b)
				return false;
			else
				b.clear(),lx=0;
		} 
	}
	return true;
}
int main()
{
	while(~scanf("%s",s+1))
	{
		ls=strlen(s+1);
		if( ls==1 && s[1]=='.') break;
		
		int ans=0,f=0;
		for(int i=1;i<=ls;i++)
		{
			if(ls%i==0)
			{
				if(check(i))
				{
					ans=max(ans,ls/i);
					f=1;
					break;
				}
			}
		}
		if(f)
			cout<<ans<<endl;
		else
			cout<<"1"<<endl;
	}
	return 0;
 } 
posted @ 2021-07-19 16:20  斯文~  阅读(18)  评论(0)    收藏  举报

你好!