-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (35 loc) · 1.07 KB
/
Solution.java
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
32
33
34
35
36
37
38
39
40
class Solution {
public int repeatedStringMatch(String A, String B) {
int lengthA = A.length(),
lengthB = B.length(),
i = 0,
j = 0;
int[] next = new int[lengthB];
while (i < lengthB) {
if (i == 0 || (B.charAt(i) != B.charAt(j) && j == 0)) {
next[i] = 0;
} else if (B.charAt(i) == B.charAt(j)) {
next[i] = ++j;
} else if (B.charAt(i) != B.charAt(j) && j > 0) {
j = next[j - 1];
continue;
}
i++;
}
i = j = 0;
while (j < lengthB) {
if (A.charAt(i % lengthA) == B.charAt(j)) {
i++;
j++;
} else if (j == 0) {
i++;
} else if (j > 0) {
j = next[j - 1];
}
if (i >= lengthA + lengthB) {
return -1;
}
}
return i % lengthA > 0 ? i / lengthA + 1 : i / lengthA;
}
}