796. Rotate String* (旋转字符串)
https://leetcode.com/problems/rotate-string/
题目描述
We are given two strings, A
and B
.
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
.
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
Note:
A
andB
will have length at most100
.
C++ 实现 1
最简洁的实现方法是, 利用 A + A
组成的字符串可以表示出 A
的所有经 shift 生成的字符串, 比如:
A = 'abc'
A + A = 'abcabc'
在该字符串中, 'abc', 'bca', 'cab' 均存在
此时只需要判断 B
是否在 A + A
中:
class Solution {
public:
bool rotateString(string A, string B) {
return (A.size() == B.size()) && (A + A).find(B) != -1;
}
};
C++ 实现 2
如果实在没有想到上面的解法, 使用很直接的思路, 将 shift
实现, 然后判断每个 shift
生成的字符串是否和 B
相等.
class Solution {
private:
string shift(const string &s) {
if (s.empty()) return s;
auto size = s.size();
return s.substr(size - 1, 1) + s.substr(0, size - 1);
}
public:
bool rotateString(string A, string B) {
if (A == B) return true;
auto num = A.size();
for (int i = 1; i < num; ++ i) {
A = shift(A);
if (A == B) return true;
}
return false;
}
};