#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”).
这道题求的是字符串A重复几次可以包含子串B. includes用来找一个字符串是否为另一个字符串的子串,repeat返回重读了n次的新子串。
var repeatedStringMatch = function(A, B) {
let result = Math.ceil(B.length / A.length)
const [str1, str2] = [A.repeat(result), A.repeat(result + 1)]
if (str1.includes(B)) return result
if (str2.includes(B)) return result + 1
return -1
};