[LeetCode] 796. Rotate String

旋转字符串。题意是给两个字符串A和B,请判断B是否是经由A旋转过若干次而得到的。例子,

Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true

Example 2:
Input: A = 'abcde', B = 'abced'
Output: false

思路是将两个A拼接在一起,看看B是否存在于这个拼接后的字符串中。

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * @param {string} A
 3  * @param {string} B
 4  * @return {boolean}
 5  */
 6 var rotateString = function (A, B) {
 7     if (A.length != B.length) return false;
 8     let combine = A.concat(A);
 9     return combine.includes(B);
10 };

 

Java实现

1 class Solution {
2     public boolean rotateString(String A, String B) {
3         return A.length() == B.length() && (A + A).contains(B);
4     }
5 }

 

posted @ 2020-03-09 14:39  CNoodle  阅读(230)  评论(0编辑  收藏  举报