[LeetCode] Rotate String 旋轉字符串


 

We are given two strings, A and B.

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 and B will have length at most 100.

 

這道題給了我們兩個字符串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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM