问题
现在我们定义一种新的名词叫做旋转词。对于一个字符串A,将A的前面任意一部分挪到后面形成的字符串称为A的旋转词,比如A=“12345”,那么”51234“”45123“”34512“”23451“即为A的旋转词。现在给出两个字符串A和B,请判断A和B是否互为旋转词。
在输入的首行输入A,接着输入B。然后输出判断结果,如果A和B互为旋转词,那么输出yes,如果A和B互不为旋转词语,输出no
输入
第一行输入A,第二行输入B
输出
输出判断结果
思路
将一个字符串首位相连,从前面遍历,与另一个相比较,当对应相同时,一直比较相同的数量是字符串的长度
1234512345 与 23451
1234512345 与34512
…
…
1234512345与51234
代码
#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 << "no" << 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 << "yes" ;
return 0;
}
else
{
j = 0;
i = begin;
}
}
}
cout << "no" ;
return 0;
}