Leetcode 686. Repeated String Match
686. Repeated String Match
Given two strings a
and b
, return the minimum number of times you should repeat string a
so that string b
is a substring of the repeated string. If it is impossible for b
to be a substring of the repeated a
, return -1
.
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We need to repeat "abcd" three times to get "abcdabcdabcd", which contains "cdabcdab".
Example 2:
Input: a = "a", b = "aa"
Output: 2
Explanation: We need to repeat "a" two times to get "aa", which contains "aa".
Constraints:
a
and b
consist of lower-case English letters.a
and b
be of equal length?
a
need to be contiguous to form b
?
a
should ensure that b
is a contiguous substring within the repeated string formed by a
.a
that would cover the length of b
. This would be ceil(len(b) / len(a))
.a
an extra time (or two), because there may be overlap where b
starts at the end of one repetition of a
and continues into the beginning of the next.a
at most ceil(len(b) / len(a)) + 2
times and check if b
is a substring within these repetitions.-1
.#include <iostream>
#include <string>
#include <cmath>
class Solution {
public:
int repeatedStringMatch(std::string a, std::string b) {
int repeatedCount = std::ceil((double)b.size() / a.size());
std::string repeatedA = a;
// Initial repeated string to cover length of b
for (int i = 1; i < repeatedCount; ++i) {
repeatedA += a;
}
// Check if b is a substring of current repeatedA
if (repeatedA.find(b) != std::string::npos) return repeatedCount;
// Add one more repetition of a to check
repeatedA += a;
if (repeatedA.find(b) != std::string::npos) return repeatedCount + 1;
// Add two repetitions of a to consider edge overlaps
repeatedA += a;
if (repeatedA.find(b) != std::string::npos) return repeatedCount + 2;
// If still not found
return -1;
}
};
int main() {
Solution sol;
std::string a = "abcd";
std::string b = "cdabcdab";
std::cout << sol.repeatedStringMatch(a, b); // Output: 3
return 0;
}
a
up to the length ( O(n \times m) ) where n
is the length of a
and m
is the number of repetitions (at most ( \lceil \frac{m}{n} \rceil + 2 )).Overall, the time complexity is ( O(n \times m) ).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?