字符串移位包含问题

描述:

对于一个字符串来说,定义一次循环移位操作为:将字符串的第一个字符移动到末尾形成新的字符串。

给定两个字符串s1和s2,要求判定其中一个字符串是否是另一字符串通过若干次循环移位后的新字符串的子串。例如CDAA是由AABCD两次移位后产生的新串BCDAA的子串,而ABCD与ACBD则不能通过多次移位来得到其中一个字符串是新串的子串。

输入:

一行,包含两个字符串,中间由单个空格隔开。字符串只包含字母和数字,长度不超过30。

输出:

如果一个字符串是另一字符串通过若干次循环移位产生的新串的子串,则输出true,否则输出false。

样例输入:

AABCD CDAA

样例输出

true

代码如下:

思路一:

C++语言,可直接应用string类型进行操作。

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	string s1,s2,s;
	cin>>s1>>s2;
	if(s1.size()<s2.size()){
		swap(s1,s2);
	}
	if((s1+s1).find(s2)==-1)
	cout<<"false"<<endl;
	else cout<<"true"<<endl;
	return 0;
}

思路二:

C语言,利用循环模除进行匹配。

#include <stdio.h>
#include <string.h>
 
#define N 30
char s[N + 1], t[N + 1];
 
int check(char s1[], int lens1, char s2[], int lens2)
{
    int i, j;
 
    for(i = 0; i < lens1; i++) {
        for(j = 0; j < lens2; j++) {
            if(s[(i + j) % lens1] != s2[j])
                break;
        }
        if(j == lens2)
            return 1;
    }
 
    return 0;
}
 
int main()
{
    int lens1, lens2, ans;
 
    scanf("%s%s", s1, s2);
 
    /* 计算字符串长度,调用函数check()时,长字符串作为第1个参数 */
    lens1 = strlen(s1);
    lens2 = strlen(s2);
    if(lens1 > lent)
        ans = check(s1, lens1, s2, lens2);
    else
        ans = check(s2, lens2, s1, lens1);
 
    printf("%s\n", ans ? "true" : "false");
 
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值