给定两个字符串s1,s2,请编写代码检查s2是否为s1旋转而成

1.8:假定有一个方法isSubstring,可检查一个单词是否为其他字符串的子串。给定两个字符串s1,s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次isSubstring

比如waterbottle是erbottlewat旋转后的字符串

解法:

假定s2由s1旋转而成,那么,我们就可以找出旋转点在哪,例如,若以wat对waterbottle旋转,就会得到erbottlewat.在旋转字符串时,我们会把s1切分成两部分:x和y,并将它们重新组合成s2

s1=xy=waterbottle

x=wat

y = erbottle

s2=yx=erbottlewat

因此,我们需要确认有没有办法将s1切分成x和y,以满足xy=s1和yx=s2。不论x和y之间的分割点在何处,我们会发现yx肯定是xyxy的子串,也即s2总是s1s1的子串

解决方案:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
#include <cstdio>    // getchar()

using  namespace std;

/************************************************************************/
// 函数名称:isRotation_2
// 函数目的:判断字符串是否是转换字符串
// 函数参数:s1 s2
// 函数返回:true:是转置字符串
// 使用条件:
/************************************************************************/

bool isRotation_2( const string& s1,  const string& s2)
{
    size_t len = s1.length();
     if (len == s2.length() && len >  0){
        string s1s1 = s1 + s1;   // the key point
        size_t found = s1s1.find(s2);
         if ( found != std::string::npos )  return  true;
    }

     return  false;
}

int main()
{
     char s1[] =  "waterbottle";
     char s2[] =  "erbottlewat";

    cout <<  "s1 = " << s1 << endl;
    cout <<  "s2 = " << s2 << endl;

    cout <<  "调用转换字符函数isRotation_2()判断之后:" << endl;
    cout << (isRotation_2(s1, s2) ?  "true" :  "false") << endl;

    getchar();
     return  0;
}

运行结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值