We are given two strings, A
and B
.html
A shift on A
consists of taking string A
and moving the leftmost character to the rightmost position. For example, if A = 'abcde'
, then it will be 'bcdea'
after one shift on A
. Return True
if and only if A
can become B
after some number of shifts on A
.spa
Example 1: Input: A = 'abcde', B = 'cdeab' Output: true Example 2: Input: A = 'abcde', B = 'abced' Output: false
Note:code
A
and B
will have length at most 100
.
這道題給了咱們兩個字符串A和B,定義了一種偏移操做,以某一個位置將字符串A分爲兩截,並將兩段調換位置,若是此時跟字符串B相等了,就說明字符串A能夠經過偏移獲得B。如今就是讓咱們判斷是否存在這種偏移,那麼最簡單最暴力的方法就是遍歷全部能將A分爲兩截的位置,而後用取子串的方法將A斷開,交換順序,再去跟B比較,若是相等,返回true便可,遍歷結束後,返回false,參見代碼以下:htm
解法一:blog
class Solution { public: bool rotateString(string A, string B) { if (A.size() != B.size()) return false; for (int i = 0; i < A.size(); ++i) { if (A.substr(i, A.size() - i) + A.substr(0, i) == B) return true; } return false; } };
還有一種一行完成碉堡了的方法,就是咱們其實能夠在A以後再加上一個A,這樣若是新的字符串(A+A)中包含B的話,說明A必定能經過偏移獲得B。就好比題目中的例子,A="abcde", B="bcdea",那麼A+A="abcdeabcde",裏面是包括B的,因此返回true便可,參見代碼以下:leetcode
解法二:字符串
class Solution { public: bool rotateString(string A, string B) { return A.size() == B.size() && (A + A).find(B) != string::npos; } };
參考資料:get
https://leetcode.com/problems/rotate-string/solution/string
https://leetcode.com/problems/rotate-string/discuss/118696/C++-Java-Python-1-Line-Solutionit