【字符串】判断s2是否是s1的旋转字符串

题目
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”的旋转字符串。
 

思路:

只需要get一个点:s1+s1则包含了s1的所有旋转字符串,所以等效于判断s2是否是s1+s1的子串

//判断s2是不是s1的子串
bool isSubstring(string s1, string s2){
    if(s1.find(s2) != string::npos) return true;
    else return false;
}

//防范一下,以及调用:isSubstring(s1+s1, s2)
bool isRotation(string s1, string s2){
    if(s1.length() != s2.length() || s1.length()<=0)
        return false;
    return isSubstring(s1+s1, s2);
}

比如:

s1 = waterbottle,某个旋转字符串是 erbottlewat

s1 + s1 = waterbottlewaterbottle

猜你喜欢

转载自blog.csdn.net/m0_38033475/article/details/92380657