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; } |
运行结果: