C++ simple solution = Implement strStr() idea


  • 0
    J

    Instead of Input: haystack = "hello", needle = "ll",
    we have input: A = "abcd", B = "cdab". One can image now the haystack is AA...A = "abcd.abcd...abcd"and needle is B = "cdab"

     int repeatedStringMatch(string A, string B) {
            int m = A.size(), n = B.size();
            for (int i = 0; i < m; i++) {
                int j = 0;
                while (j < n && A[(i + j) % m] == B[j]) j++;
                if (j == n) return ((i + j - 1)/ m) + 1;
            }
            return -1;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.