给定两个字符串s1,s2,请编写代码检查s2是否为s1旋转而成
2015-10-12 22:07
543 查看
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的子串
解决方案:
运行结果:
比如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; } |
相关文章推荐
- JAVA学习
- ios学习之动画中JNWSpringAnimation第三方库
- php的self关键字和静态方法调用
- 游戏系统开发笔记(三)——通用代码库
- SQLSTATE[HY000] [2002] No such file or directory php连接mysql失败
- Java考题
- Scala学习笔记16【Scala闭包代码实例】
- [Django模板系统]大致了解Django的模板系统
- Xcode和github入门详细教程
- 【C语言】求最大最小值
- java hashtable 和 hashmap的区别
- Struts2-访问web 资源
- 马士兵Java课堂笔记-1-float精度问题
- 树莓派编程wiringPi控制电子数码管显示循环0~9
- 项目36.5 有多少符号
- 小小君的C语言第三课
- 【C++】装饰器模式
- qt多线程信号槽传输方式
- Windows下安装Django
- hdoj 2032 杨辉三角 c++