[LeetCode] 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 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”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
private:
int isTwo(string &a, string &b) {
size_t pos = a.length() - 1;
for(; b.find(a.substr(pos)) != string::npos; --pos) {}
for(int aPos = pos, bPos = a.length() - pos; aPos >= 0 && bPos < b.length(); --aPos, ++bPos) {
if(a[aPos] != b[bPos])
return -1;
}
return 2;
}

int getLoop(string &a, string &b, size_t& pos) {
int res = pos ? 1 : 0, i = 0;
for(; pos < b.length(); pos++, i++) {
if(b[pos] != a[i])
return -1;
if(i == a.length() - 1) {
i = -1;
res++;
}
}

return i ? res + 1 : res;
}
public:
int repeatedStringMatch(string a, string b) {
size_t pos = b.find(a, 0), prev = 0;
return b.length() <= a.length() ? a.find(b) != string::npos ? 1 : isTwo(a, b) : pos != string::npos && a.find(b.substr(0, pos), 0) == string::npos ? -1 : pos == string::npos ? isTwo(b, a) : getLoop(a, b, pos);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/20/PS/LeetCode/repeated-string-match/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.