686. Repeated String Match
1. Description
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 it. If it is impossible for b to be a substring of a after repeating it, return -1.
Notice: string “abc” repeated 0 times is “”, repeated 1 time is “abc” and repeated 2 times is “abcabc”.
2. Example
Example 1:
Input: a = “abcd”, b = “cdabcdab”
Output: 3
Explanation: We return 3 because by repeating a three times “abcdabcdabcd”, b is a substring of it.
Example 2:
Input: a = “a”, b = “aa”
Output: 2
3. Constraints
- 1 <= a.length, b.length <= $10^4$
- a and b consist of lowercase English letters.
4. Solutions
Find
class Solution {
public:
int repeatedStringMatch(const string &a, const string &b) {
string joint_str;
while (joint_str.size() <= b.size()) {
joint_str.append(a);
}
joint_str.append(a);
size_t found_index = joint_str.find(b);
return found_index == string::npos
? -1
: (b.size() + found_index - 1) / a.size() + 1; // upper bound
}
};