题目:
如果一个字符串str,把字符串str前面任意的部分挪到后面形成的字符串叫做str的旋转词。
如str="12345",str的旋转词有"12345"、"23451"、"34512"、"45123"、"51234"。
给定两个字符串a和b,请判断a和b是否互为旋转词。
举例:
a="cdab",b="abcd",返回true;
a="1ab2",b="ab12",返回false;
a="2ab1",b="ab12",返回true。
要求:
如果a和b长度不一样,那么a和b必然不互为旋转词,可以直接返回false。
当a和b长度一样,都为N时,要求解法的时间复杂度为O(N)。
难度:★
思路:
第一想法是,在b中找到与a的第一个字符相等的字符,然后进行移位比较,如果遍历结束仍相等,则返回true;否则返回false。
但是!这样做法有两个缺点,一是找到的相等的字符不一定就是a的开始,如a="abcda",b="aabcd";二是就算找对了,b从找到的位置比较到字符串末尾后,还要回到b的首字符继续进行比较,代码编写比较繁琐。
书本上的参考思路是将两个b拼接在一起赋值给c,查看c中是否包含字符串a,若包含,则返回true;否则返回false。
因为,如果一个字符串str长度为N,在通过str生成的dou_str中,任意长度为N的子串都是str的旋转词。
而对于如何判断字符串c中是否包含字符串a,书上介绍使用KMP算法,可达到时间复杂度O(n)。
本人目前水平有限,现在还不适合了解该算法,故使用自己的方法去解决。。。双重循环啊。。。
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
getline(cin, str1);
getline(cin, str2);
int len1 = str1.size(), len2 = str2.size();
if (len1 != len2)
{
cout << "N" << endl;
system("pause");
return 0;
}
string str = str2 + str2;
int i, j = 0, count, begin;
for (i = 0; i < 2 * len2; i++)
{
if (str1[j] == str[i])
{
begin = i;
count = 1;
while (str1[++j] == str[++i])
count++;
if (count == len1)
{
cout << "Y" << endl;
system("pause");
return 0;
}
else
{
j = 0;
i = begin;
}
}
}
cout << "N" << endl;
system("pause");
return 0;
}