686. Repeated String Match
int repeatedStringMatch(string A, string B) { // time: O(n1 * n2); space: O(n2)
int n1 = A.size(), n2 = B.size(), cnt = 1;
string t = A;
while (t.size() < n2) {
t += A;
++cnt;
}
if (t.find(B) != string::npos) return cnt;
t += A;
return (t.find(B) != string::npos) ? ++cnt : -1;
}int repeatedStringMatch(string A, string B) { // time: O(n1 * n2); space: O(n2)
int n1 = A.size(), n2 = B.size();
string t = A;
for (int cnt = 1; cnt <= n2 / n1 + 2; ++cnt) {
if (t.find(B) != string::npos) return cnt;
t += A;
}
return -1;
}Last updated