Q1.8 Check if s2 is a rotation of s1

时间:2022-09-06 19:34:36

Q: Assume you have a method isSubstring which checks if one word is asubstring of another. Given two strings, s1 and s2, write code tocheck if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).

A:

s = xy, 其中x、y分别是子串, 旋转之后s' = yx , 可以发现无论从什么位置开始旋转, yx永远是xyxy是的子串。

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

bool isSubstring(string s, string t) {
	if (s.find(t) != string::npos) return true;
	else return false;
}
bool isRotation(string s1, string s2) {
	if (s1.length() != s2.length() || s1.length() < 1) {
		return false;
	}
	return isSubstring(s1+s1, s2);
}
int main() {
	string s1 = "waterbottle";
    string s2 = "erbottlewat";
    cout<<isRotation(s1, s2)<<endl;
}