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