旋转字符串:把字符串前面的若干个字符移动到字符串的尾部;例如deabc就是abcde的一个旋转字符串。
题目:假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串。
分析:要用判断子串的函数来判断s1是否为s2的旋转字符串,如果s1是s2的旋转字符串,则s1一定是s2+s2的子串。其实s2+s2包含了所有s2的旋转字符串。
代码:
#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(s2 + s2, s1);
}
int main(){
string s1 = "pleap";
string s2 = "apple";
cout << isRotation(s2, s1) << endl;
return 0;
}