题目大意:给你两个字符串A, B, 问能否通过旋转A得到B。
Problem:
https://leetcode.com/problems/rotate-string/description/
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
.
1 2 3 4 5 6 7 |
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
.
Solution 1: Brute Force
Time complexity: O(n^2)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Running time: 3 ms class Solution { public: bool rotateString(string A, string B) { if (A.length() != B.length()) return false; for (int i = 1; i < A.length(); ++i) if (check(A, B, i)) return true; return false; } private: bool check(const string& A, const string& B, int offset) { for (int i = 0; i < A.length(); ++i) if (A[(i + offset) % A.length()] != B[i]) return false; return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment