1.8 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 si using only one call to isSubstring (e.g.,"waterbottle"is a rotation of "erbottlewat").
這道題給定兩個字串,讓我們判斷其中一個是否是另一個的旋轉字串,並給了我們一個例子來說明旋轉字串,比如waterbottle是erbottlewat的旋轉字串。而且還給我們了一個isSubstring函式可以呼叫,這個函式是用來判斷一個字串是否是另一個字串的子字串,不過規定了我們只能呼叫一次。這題要用到一個小技巧,就是加入我們將s1重複兩次,變成s1s1,那麼s2如果是s1s1的子字串,那麼它們就互為旋轉字串,就拿題目中的梯子來分析:
若令 x = wat y = erbottle
則 s1 = xy s2 = yx
若令 s1s1 = xyxy
則 s2 一定是 s1s1的子字串
class Solution { public: bool isRotation(string s1, string s2) { if (s1.size() != s2.size() || s1.empty()) return false; string s1s1 = s1 + s1; return isSubstring(s1s1, s2); } };