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

来源:互联网 发布:淘宝网美都袋鼠皮相 编辑:程序博客网 时间:2024/05/20 07:50

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;}



0 0
原创粉丝点击