LeetCode 796 Rotate String
传送门:LeetCode 796
题目分析
题目原文:
We are given two strings,
A
andB
.A shift on A consists of taking string
A
and moving the leftmost character to the rightmost position. For example, ifA = 'abcde'
, then it will be'bcdea'
after one shift onA
. ReturnTrue
if and only ifA
can becomeB
after some number of shifts onA
.
Example 1: Input: A = 'abcde', B = 'cdeab' Output: true Example 2: Input: A = 'abcde', B = 'abced' Output: false
题目就是一个字符串经过移位
操作操作与另一个字符串相等,类似循环移位,判断给定的两个字符串是否满足这种关系。
思考
题目的要求很简单,对一个字符串进行移位
操作来使其与另一个字符串相等,移位操作让我想到了使用循环队列的操作,把队头的元素加到队尾,判断是否相等,思路就是使用循环队列的思想进行比较,时间复杂度应该是O(
O2
O
2
)。
代码实现
using ull = unsigned long long;
class Solution {
public:
bool rotateString(string A, string B) {
if (A.length() != B.length()) {
return false;
}
ull length = A.length();
// 旋转判断
for (int i = 0; i < length; ++i) {
bool same = true;
for (int j = 0; same && j < length; ++j) {
if (A[j] != B[(j + i) % length]) {
same = false;
}
}
// 相同返回true
if (same) {
return true;
}
}
// 移位全部试探失败
return false;
}
};
感想
略