Given two strings a and b, return the minimum number of times you should repeat stringaso that stringbis 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".
We want to repeat string a the minimum number of times so that b is a substring of the result. The minimum number of repeats is ceil(len(b)/len(a)), but we may need one or two more repeats to cover all cases.
#include<string>usingnamespace std;
intrepeatedStringMatch(string a, string b) {
string s = a;
int count =1;
while (s.size() < b.size()) {
s += a;
count++;
}
if (s.find(b) != string::npos) return count;
s += a;
if (s.find(b) != string::npos) return count +1;
return-1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import"strings"funcrepeatedStringMatch(a, bstring) int {
s:=acount:=1for len(s) < len(b) {
s+=acount++ }
ifstrings.Contains(s, b) {
returncount }
s+=aifstrings.Contains(s, b) {
returncount+1 }
return-1}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicclassSolution {
publicintrepeatedStringMatch(String a, String b) {
StringBuilder sb =new StringBuilder(a);
int count = 1;
while (sb.length() < b.length()) {
sb.append(a);
count++;
}
if (sb.indexOf(b) !=-1) return count;
sb.append(a);
if (sb.indexOf(b) !=-1) return count + 1;
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
funrepeatedStringMatch(a: String, b: String): Int {
val sb = StringBuilder(a)
var count = 1while (sb.length < b.length) {
sb.append(a)
count++ }
if (sb.contains(b)) return count
sb.append(a)
if (sb.contains(b)) return count + 1return -1}
1
2
3
4
5
6
7
8
9
10
11
12
defrepeatedStringMatch(a: str, b: str) -> int:
s = a
count =1while len(s) < len(b):
s += a
count +=1if b in s:
return count
s += a
if b in s:
return count +1return-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fnrepeated_string_match(a: &str, b: &str) -> i32 {
letmut s = a.to_string();
letmut count =1;
while s.len() < b.len() {
s += a;
count +=1;
}
if s.contains(b) {
return count;
}
s += a;
if s.contains(b) {
return count +1;
}
-1}
1
2
3
4
5
6
7
8
9
10
11
12
functionrepeatedStringMatch(a: string, b: string):number {
lets=a;
letcount=1;
while (s.length<b.length) {
s+=a;
count++;
}
if (s.includes(b)) returncount;
s+=a;
if (s.includes(b)) returncount+1;
return-1;
}