LeetCode每日一题:旋转字符串(No.796)

497 阅读1分钟

题目:旋转字符串


给定两个字符串, A 和 B。
A 的旋转操作就是将 A 最左边的字符移动到最右边。
例如, 若 A = 'abcde',在移动一次之后结果就是'bcdea' 。  
如果在若干次旋转操作之后,A 能变成B,那么返回True。

示例:


示例 1:
输入: A = 'abcde', B = 'cdeab'
输出: true

示例 2:
输入: A = 'abcde', B = 'abced'
输出: false

思考:


这题先想到的就是按照题中的移动方法循环截取字符串A拼接后再与B比较,相同则为true,否则即为false。

实现:


 class Solution {
    public boolean rotateString(String A, String B) {
        if (A.equals(B)) {
            return true;
        }
        for (int count = 0; count < A.length(); count++) {
            String newStr = A.substring(count) + A.substring(0, count);
            if (newStr.equals(B)) {
                return true;
            }
        }
        return false;
    }
}

再思考:


其实这题还有更简单的做法。就是如果A旋转后能与B相等,就说明B一定是A+A的字串。
所以就有下面的方法。

再实现:


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