[LeetCode] 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
.
这道题给了我们两个字符串A和B,定义了一种偏移操作,以某一个位置将字符串A分为两截,并将两段调换位置,如果此时跟字符串B相等了,就说明字符串A可以通过偏移得到B。现在就是让我们判断是否存在这种偏移,那么最简单最暴力的方法就是遍历所有能将A分为两截的位置,然后用取子串的方法将A断开,交换顺序,再去跟B比较,如果相等,返回true即可,遍历结束后,返回false,参见代码如下:
解法一:
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即可,参见代码如下:
解法二:
class Solution { public: bool rotateString(string A, string B) { return A.size() == B.size() && (A + A).find(B) != string::npos; } };
参考资料:
https://leetcode.com/problems/rotate-string/solution/
https://leetcode.com/problems/rotate-string/discuss/118696/C++-Java-Python-1-Line-Solution
相关文章
- Java实现 LeetCode 403 青蛙过河
- Java实现 LeetCode 392 判断子序列
- Java实现 LeetCode 338 比特位计数
- Java实现 LeetCode 28 实现strStr()
- C#基础知识系列一(goto、i++、三元运算符、ref和out、String和string、重载运算符)
- 1,字符是否为空,2,比较两个字符大小。String.Compare(String, String)。string.IsNullOrEmpty(string)
- LeetCode:151_Reverse Words in a String | 字符串中单词的逆反 | Medium
- [LeetCode] Reverse Vowels of a String
- [LeetCode] Reverse Words in a String
- [LeetCode] String to Integer (atoi)
- LeetCode-937. 重新排列日志文件【stable_sort(),自定义排序】
- C# string.Format 和 String.Format 的区别
- Leetcode 2022. 将一维数组转变成二维数组
- Leetcode 204. 计数质数(太妙了)
- Leetcode 只出现一次的数字
- LeetCode——Symmetric Tree
- leetcode 557. Reverse Words in a String III
- 【Leetcode刷题Python】714. 买卖股票的最佳时机含手续费
- 【LeetCode】208.实现Trie(前缀树)