2050:【例5.20】字串包含
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 33301 通过数: 13981
【题目描述】
字符串移位包含问题。
对于一个字符串来说,定义一次循环移位操作为:将字符串的第一个字符移动到末尾形成新的字符串。
给定两个字符串s1和s2,要求判定其中一个字符串是否是另一字符串通过若干次循环移位后的新字符串的子串。例如CDAA
是由AABCD
两次移位后产生的新串BCDAA
的子串,而ABCD
与ACBD
则不能通过多次移位来得到其中一个字符串是新串的子串。
【输入】
一行,包含两个字符串,中间由单个空格隔开。字符串只包含字母和数字,长度不超过3030。
【输出】
如果一个字符串是另一字符串通过若干次循环移位产生的新串的子串,则输出true
,否则输出false
。
【输入样例】
AABCD CDAA
【输出样例】
true
参考代码:C++
#include<iostream>
#include<string>
using namespace std;
int main() {
string s1, s2;
cin >> s1 >> s2;
if (s1.length() < s2.length()) {//变成都从长的中找短的
swap(s1, s2);
}
for (int i = 0; i < s1.size(); i++) {
if (s1.find(s2) != -1) {
cout << "true" << endl;
return 0;
}
char t = s1[0];
s1.erase(0, 1);
//s1 += t;
s1.push_back(t);//从数组尾部插入元素
}
cout << "false" << endl;
return 0;
}
第二种方法:环
#include<iostream>
#include<string>
using namespace std;
//线性模拟环(核心:首尾相连,循环模拟或者将原序列扩增为原来2倍
int main() {
string s1, s2;
cin >> s1 >> s2;
if (s1.length() < s2.length()) {
swap(s1, s2);
}
s1 += s1;
if (s1.find(s2) != -1) {
cout << "true" << endl;
}
else cout << "false" << endl;
return 0;
}