1. 程式人生 > >Q1.8 Check if s2 is a rotation of s1

Q1.8 Check if s2 is a rotation of s1

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