A24173. 字串包含
填空题
中等
知识点
题目描述
字串包含
题目描述
字符串移位包含问题。
对于一个字符串来说,定义一次循环移位操作为:将字符串的第一个字符移动到末尾形成新的字符串。
给定两个字符串s1和s2,要求判定其中一个字符串是否是另一字符串通过若干次循环移位后的新字符串的子串。
例如CDAA是由AABCD两次移位后产生的新串BCDAA的子串,而ABCD与ACBD则不能通过多次移位来得到其中一个字符串是新串的子串。
输入
一行,包含两个字符串,中间由单个空格隔开。字符串只包含字母和数字,长度不超过30。
输出
如果一个字符串是另一字符串通过若干次循环移位产生的新串的子串,则输出true,否则输出false。
输入样例
AABCD CDAA输出样例
true参考答案
#include<bits/stdc++.h>
using namespace std;
bool isSubStr(string s1, string s2)//s2是不是s1的子串
{
int l1 = s1.length(), l2 = s2.length();
for(int i = 0; i <= l1 - l2; ++i)
{
if(s1.substr(i, l2) == s2)
return true;
}
return false;
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
if(s1.length() < s2.length())//让s1是较长的字符串,s2是较短的字符串
swap(s1, s2);
for(int i = 0; i < s1.length(); ++i)
{
if(isSubStr(s1, s2))//判断s2是否是s1的子串
{
cout << "true";
return 0;
}
//s1整体向左循环移位一格,s1[0]移动到最末尾
s1.push_back(s1[0]);//将第一个字符添加到末尾
s1.erase(s1.begin());//删除第一个字符
}
cout << "false";
return 0;
}答案解析
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s1[35], s2[35], t[35], c;
cin >> s1 >> s2;
int l1, l2, tl;
l1 = strlen(s1);
l2 = strlen(s2);
if(l1 < l2)//让s1是较长的字符串,s2是较短的字符串
{//如果s1比s2短,那么二者交换
strcpy(t, s1);
strcpy(s1, s2);
strcpy(s2, t);
swap(l1, l2);
}
for(int i = 0; i < l1; ++i)
{
if(strstr(s1, s2) != NULL)//判断s2是否是s1的子串
{
cout << "true";
return 0;
}
//s1整体向左循环移位一格,s1[0]移动到最末尾
c = s1[0];
for(int j = 0; j < l1 - 1; ++j)
s1[j] = s1[j+1];
s1[l1-1] = c;
}
cout << "false";
return 0;
}
上一题
下一题