您的位置:首页 > 其它

【Cracking the coding interview】Q1.8(旋转字符串)

2013-12-23 21:52 387 查看
Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring ( i.e., “waterbottle”
is a rotation of “erbottlewat”).

假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。

思路: erbottlewat一定是waterbottle+waterbottle的子串

#include <iostream>
#include <string>
using namespace std;

bool isSubstring(string s1, string s2){
if(s1.find(s2) != string::npos) return true;
else return false;
}
bool isRotation(string s1, string s2){
if(s1.length() != s2.length() || s1.length()<=0)
return false;
return isSubstring(s1+s1, s2);
}

int main(){
string s1 = "apple";
string s2 = "pleap";
cout<<isRotation(s1, s2)<<endl;
cout<<string::npos<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: