Repeated String Match -LeetCode#686 | 8lovelife's life
0%

Repeated String Match -LeetCode#686

FIRST -Time Limit Exceeded

1
2
3
4
5
6
7
8
9
public static int repeatedStringMatch(String a, String b) {
for (int i = 1; i <= b.length(); i++) {
String repeatStr = a.repeat(i);
if (repeatStr.contains(b)) {
return i;
}
}
return -1;
}

SECOND -AC 10.57%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static int repeatedStringMatch(String a, String b) {
StringBuilder sb = new StringBuilder();
int count = 0;
while (sb.length() < b.length()) {
sb.append(a);
count++;
}
if (sb.indexOf(b) >= 0) {
return count;
}
sb.append(a);
count++;
if (sb.indexOf(b) >= 0) {
return count;
}
return -1;
}

THREE -AC 98.53%

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
public static int repeatedStringMatch(String a, String b) {
int[] freq = new int[26];
for (char c : a.toCharArray()) {
freq[c - 'a']++;
}
for (char c : b.toCharArray()) {
if (freq[c - 'a'] == 0) {
return -1;
}
}
StringBuilder sb = new StringBuilder();
int count = 0;
while (sb.length() < b.length()) {
sb.append(a);
count++;
}
if (sb.indexOf(b) >= 0) {
return count;
}
sb.append(a);
count++;
if (sb.indexOf(b) >= 0) {
return count;
}
return -1;
}