51nod 1347 旋转字符串

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
 收藏
 关注

S[0...n-1]是一个长度为n的字符串,定义旋转函数Left(S)=S[1…n-1]+S[0].比如S=”abcd”,Left(S)=”bcda”.一个串是对串当且仅当这个串长度为偶数,前半段和后半段一样。比如”abcabc”是对串,”aabbcc”则不是。

现在问题是给定一个字符串,判断他是否可以由一个对串旋转任意次得到。


Input
第1行:给出一个字符串(字符串非空串,只包含小写字母,长度不超过1000000)
Output
对于每个测试用例,输出结果占一行,如果能,输出YES,否则输出NO。
Input示例
aa
ab
Output示例
YES
NO

首先想到了枚举旋转字符串 

进行逐个判断的方式验证

在试了几组样例后

发现是对串移不移都是对串

反之怎么移也不是对串

所以以下代码删去枚举部分 

直接判一次即可

#include <iostream>
#include <cstring>
using namespace std;
bool duistring(string a,int len)
{
	for(int i = 0, j = len/ 2; i < len / 2; i++, j++)
	{
		if(a[i] != a[j])
			return false;
	}
	return true;
}
int main()
{
	ios::sync_with_stdio(false);
	string a;
	cin>>a;
	char tmp;
	int len = a.length();
	int flag = len;
	if( len % 2 != 0)
	{
		cout<<"NO"<<endl;
		return 0;
	}
	else
	{
		if(duistring(a,len))
		{
			cout<<"YES"<<endl;
			return 0;
		}
		/*else
		{
			while(flag --)
			{
				tmp = a[0];
				a.erase(a.begin(),a.begin()+1);
				a = a + tmp;
				cout<<a<<endl;
				if(duistring(a,len))
				{
					cout<<"YES"<<endl;
					return 0;
				}
			}
		}*/
	}
	cout<<"NO"<<endl;
	return 0;
}


posted @ 2018-04-24 22:47  张浦  阅读(88)  评论(0编辑  收藏  举报