Google OA題目:給出使得字符串B成為字符串A重復(fù)自己構(gòu)成的字符串的子字符串,字符串A最少需重復(fù)的次數(shù)

實(shí)現(xiàn)如下函數(shù):

class Solution {public int soluition(String A, String B); }

其應(yīng)當(dāng)滿(mǎn)足的功能為:給定包含N個(gè)字母的string A和包含M個(gè)字母的string B,返回使得B成為其子字符串A需> 要重復(fù)自己的最少次數(shù)。如果無(wú)論A重復(fù)自己多少次B都無(wú)法成為其子字符串,返回-1。
如下面例子所示:

A = "abcd"
B = "cdabcdab"

這種情況下該函數(shù)需要返回3,因?yàn)锳重復(fù)3次后成為`"abcdabcdabcd",此時(shí)B是該字符串的子串。
本題假定:
N是[1...1000]內(nèi)的整數(shù)。
M是[1...1000]內(nèi)的整數(shù)。

思路分析

給定兩個(gè)string A和B,當(dāng)B的長(zhǎng)度大于A時(shí),即使在brute-force解法的情況下(既不斷重復(fù)A,看B能夠成為當(dāng)前字符串的子串),我們?nèi)匀皇紫纫_定的是B究竟能夠成為A重復(fù)自己所構(gòu)造的字符串的子串。因?yàn)檫@決定了這個(gè)循環(huán)的結(jié)束條件。

注意到B如果能夠由A不斷重復(fù)自己得到,那么B中的任何和A的長(zhǎng)度相等的連續(xù)子字符串都必須能夠由A的rotation得到。例如上面的A和B的例子中,從B中取出任何一個(gè)長(zhǎng)度為4的連續(xù)子字符串,都能夠由A的rotation產(chǎn)生。所以我們只需要產(chǎn)生A的所有rotation并將它們存入HashSet中,然后再遍歷一遍B中的所有長(zhǎng)度與A相同的連續(xù)子字符串,就可以知道B能夠由A重復(fù)自己產(chǎn)生。這一步驟的時(shí)間復(fù)雜度為:O(N + M),空間復(fù)雜度為O(N ^ 2)。

O(N + M)時(shí)間復(fù)雜度:因?yàn)槲覀冃枰謩e遍歷A的所有rotation和B的所有長(zhǎng)度與A相同的連續(xù)子字符串,分別是N種可能和M中可能,所以是O(N + M)。

O(N ^ 2)空間復(fù)雜度:因?yàn)槲覀冃枰鎯?chǔ)所有A的rotation,一共是N種,而每一種包括N個(gè)字母,所以總空間為O(N ^ 2)

當(dāng)我們確定了B一定能由A不斷重復(fù)自己得到之后,我們就只需要確定A最少需重復(fù)幾次。這一步驟當(dāng)然可以通過(guò)不斷讓A重復(fù)自己并判斷B是否是當(dāng)前字符串的子字符串實(shí)現(xiàn)。但這一方法并不是最優(yōu)解。實(shí)際上考慮到B一定是A的rotation組成的,A的最少重復(fù)次數(shù)可以在O(1)時(shí)間,O(1)空間內(nèi)實(shí)現(xiàn), 方法如下:

  1. 用HashMap而非HashSet來(lái)存儲(chǔ)A的rotation。其中Key為A的rotation,Value為A成為當(dāng)前rotation所需要的向左滾動(dòng)的步數(shù)。例如上面的例子中的A,其所構(gòu)造出的HashMap為:
{
    "abcd": 0,
    "bcda": 1,
    "cdab": 2,
    "dabc": 3,
}

這樣的情況下我們只需要判斷B中的第一個(gè)長(zhǎng)度與A相同的連續(xù)子字符串的rotation步數(shù)即可。

如果為0,則代表A只需要重復(fù)到(設(shè)A重復(fù)自己組成的字符串為A')A'.length() >= B.length()即可,既重復(fù)B.length() / A.length()向上取整次,也就是:B.length() / A.length() + (B.length() % A.length() == 0 ? 0 : 1)

如果不為0,則代表除去需要重復(fù)上面的次數(shù)之外,還需要額外的一次重復(fù)來(lái)滿(mǎn)足c的開(kāi)頭部分。如上面的例子中:A重復(fù)兩次即可滿(mǎn)足上面的第一個(gè)條件。但這個(gè)時(shí)候B的開(kāi)頭的"cd"并沒(méi)有成為子串,所以需要額外重復(fù)一次滿(mǎn)足B的開(kāi)頭。也就是三次。也就是重復(fù)次數(shù)為:1 + B.length() / A.length() + (B.length() % A.length() == 0 ? 0 : 1)。

需要注意的是,我們以上所有的討論基于B的長(zhǎng)度大于A的情況進(jìn)行。如果B的長(zhǎng)度小于A,我們只需要直接判斷B是否為A的子字符串即可。這個(gè)判斷可以通過(guò)KMP算法進(jìn)行,從而將時(shí)間控制在O(N)內(nèi)。

以上算法的代碼如下:

public class Solution {
    /**
     * Given 2 string A and B, return the minimum number A need to repeat itself in order
     * for B to become a substring of the repeated sequence of A.
     * 
     * In order for B to be able to become a substring of A's repeat, every B's substring
     * with the same length of A need to satisfy the requirement that it can be generated
     * through A's rotation. For example, A = "abcd" and B = "cdabcdab", every of B's substring
     * need to some rotations of A, e.g. "bcda", "cdab", "dabc", "abcd". 
     * 
     * If such a requirement is not satisfied, then -1 is returned to indicate that B cannot be obtained
     * through A's repeating itself. 
     * 
     * Otherwise, the minimum number of repeat needed for A is calculated as following:
     * 1. If B shares the same start pattern as A, ceil devision of B's length to A's length
     * is the minimum number of repeat needed.
     * 2. If B starts from some middle point character with A, then the minimum number of repeat
     * needed is the ceil devision of B's length to A's length plus 1. 
     */
    public static int minimumNumberRepeat(String A, String B) {
        // If A contains no character, then B cannot be obtained
        // by repeating A
        if (A == null || A.length() == 0) {
            return -1;
        }
        
        // If A is longer than B, search for B in A directly.
        if (A.length() > B.length()) {
            // repeat at most once to deal with condition like this:
            // A = "abcd", B = "da"
            for (int i = 0; i < 2; i++) {
                String curr = new String(new char[i + 1]).replaceAll("\0", A);
                if (curr.contains(B)) {
                    return i + 1;
                }
            }
            return -1;
        }
        
        HashMap<String, Integer> permutationsA = new HashMap<String, Integer>();
        permutationsA.put(A, 0);
        for (int i = 0; i < A.length() - 1; i++) {
            String permutationA = A.substring(i + 1, A.length()) + A.substring(0, i + 1);
            permutationsA.put(permutationA, i + 1);
        }
        
        // Check if any substring of B cannot be generated by A's permutation
        for (int i = 0; i <= B.length() - A.length(); i++) {
            String subB = B.substring(i, i + A.length());
            if (!permutationsA.containsKey(subB)) {
                return -1;
            }
        }
        
        // If every substring of B can be generated by A's permutation
        int rotation = permutationsA.get(B.substring(0, A.length()));
        if (rotation == 0) {
            return B.length() / A.length() + (B.length() % A.length() == 0 ? 0 : 1);
        } else {
            return 1 + B.length() / A.length() +  (B.length() % A.length() == 0 ? 0 : 1);
        }
    }
}

進(jìn)一步的思考

注意到經(jīng)過(guò)上面的分析,我們知道不論在何種情況下,A最多只需重復(fù)1 + B.length() / A.length() + (B.length() % A.length() == 0 ? 0 : 1)我們就可以判斷出B是否能成為A不斷重復(fù)自己構(gòu)成的字符串的子串。所以我們只需要使用for循環(huán)檢查這么多次即可。這種方法for循環(huán)的時(shí)間復(fù)雜度為O((M/N) * N) = O(M)for循環(huán)中檢查B是否為當(dāng)前字符串的子串可以用KMP算法實(shí)現(xiàn)worst case為O((M/N) * N) = O(M)。所以算法的時(shí)間復(fù)雜度為O(M ^ 2)。算法空間復(fù)雜度為O(M)因?yàn)槲覀冏顗那闆r下只需要存儲(chǔ)一個(gè)長(zhǎng)度大于等于M但小于M+N的字符串。

這種算法雖然時(shí)間復(fù)雜度上不如之前的算法,但勝在實(shí)現(xiàn)簡(jiǎn)單不用處理太多的特殊情況。

算法的具體實(shí)現(xiàn)如下:

public class Solution {
    public static int repeat(String A, String B) {
        // If A contains no character, then B cannot be obtained
        // by repeating A
        if (A == null || A.length() == 0) {
            return -1;
        }
        
        int totalTimes = 1 + B.length() / A.length() +  (B.length() % A.length() == 0 ? 0 : 1);
        for (int i = 0; i < totalTimes; i++) {
            String repeated = new String(new char[i + 1]).replaceAll("\0", A);
            if (repeated.contains(B)) {
                return i + 1;
            }
        }
        return -1;
    }
}

這里可能需要說(shuō)明的一點(diǎn)是上面我用來(lái)重復(fù)A所使用的代碼:String repeated = new String(new char[n]).replaceAll("\0", A)。其中n是我們想要重復(fù)A的次數(shù)。這段代碼的工作原理是這樣的:

首先我們用char[n]初始化了一個(gè)String。由于在這個(gè)char[n]數(shù)組中我們沒(méi)有給出任何初始值,所以生成的String中的每一個(gè)字符的值都為null,其中共有n個(gè)字符。接下來(lái)我們用replaceAll(regex, value)這個(gè)方法匹配所有的null,也就是"\0"并將它們都替換為A,因此也就將A重復(fù)了n次。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,769評(píng)論 0 33
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線(xiàn)程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,765評(píng)論 18 399
  • 有客戶(hù)問(wèn):發(fā)票驗(yàn)舊如何做?今天就發(fā)票驗(yàn)舊那點(diǎn)事兒與大家聊聊,希望對(duì)菜鳥(niǎo)級(jí)別的有所幫助。 感謝閱讀,隨意打賞。
    深廣創(chuàng)業(yè)家園閱讀 377評(píng)論 0 0
  • 偽命題鑄成了一個(gè)新的行業(yè),教育培訓(xùn)行業(yè)。曾經(jīng)的歲月無(wú)有一對(duì)一,無(wú)有奧數(shù),照樣出陳景潤(rùn),照樣茅以升。去年暑假我想帶孩...
    醉飲春江水閱讀 367評(píng)論 0 1