1. 程式人生 > >C#LeetCode刷題之#686-重複疊加字串匹配(Repeated String Match)

C#LeetCode刷題之#686-重複疊加字串匹配(Repeated String Match)

問題

給定兩個字串 A 和 B, 尋找重複疊加字串A的最小次數,使得字串B成為疊加後的字串A的子串,如果不存在則返回 -1。

舉個例子,A = "abcd",B = "cdabcdab"。

答案為 3, 因為 A 重複疊加三遍後為 “abcdabcdabcd”,此時 B 是其子串;A 重複疊加兩遍後為"abcdabcd",B 並不是其子串。

注意:A 與 B 字串的長度在1和10000區間範圍內。


Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:The length of A and B will be between 1 and 10000.


示例

public class Program {

    public static void Main(string[] args) {
        var A = "abcd";
        var B = "cdabcdab";

        var res = RepeatedStringMatch(A, B);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int RepeatedStringMatch(string A, string B) {
        var length = Math.Ceiling(B.Length / (double)A.Length) + 1;
        var repeat = new StringBuilder();
        for(var i = 0; i < length; i++) {
            repeat.Append(A);
            if(repeat.Length < B.Length) continue;
            if(repeat.ToString().Contains(B)) return i + 1;
        }
        return -1;
    }

}

以上給出1種演算法實現,以下是這個案例的輸出結果:

3

分析:

設字串A的長度是 m,字串B的長度是 n,由於部分執行庫的使用,以上演算法的時間複雜度應當為: O(m*n) 。