Posting this question after looking around different blogs/SO questions and still not finding an answer
I'm trying to wrap my head around a solution/algorithm used from a leetcode contest.
Here is the question:
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").
I know that rolling hash approach is the preferred way to go but I decided to start with the Boyer Moore approach.
After doing some research I learned that the following code used Boyer Moore Algorithm behind the scenes. Here is the code:
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
m = math.ceil(len(B)/len(A))
if B in A * m:
return m
elif B in A * (m + 1):
return m + 1
else:
return -1
Based on my understanding of the algorithm I'm not convinced how the above solution might be using BM approach.
I'm specifically not clear what this line
m = math.ceil(len(B)/len(A))
does and why we have to find m in this fashion. Could anyone help me here?
Thanks in advance