686. Repeated String Match

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").

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



S = A + A + A ...
check some S[0:], S[1:], ... , S[len(A)-1:] that B starts with
In order to satisfy S[len(A) - 1], we need to add an extra A


Time Complexity: O(N*(N+M))O(N∗(N+M)), where M, NM,N are the lengths of strings A, B. We create two strings A * q, A * (q+1) which have length at most O(M+N). When checking whether B is a substring of A, this check takes naively the product of their lengths.

Space complexity: As justified above, we created strings that used O(M+N)O(M+N) space.


class Solution {
    public int repeatedStringMatch(String A, String B) {
        StringBuilder sb = new StringBuilder();
        int res = 0;
        for(;sb.length() < B.length();res++) sb.append(A);
        if(sb.toString().contains(B)) return res;
        if(sb.append(A).toString().contains(B)) return res+1;
        return -1;