Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit dbd0745

Browse files
committed
Fix issue 59: Failed passing 686. Repeated String Match
add the failed test case add solution code and the ref: https://leetcode.com/problems/repeated-string-match/discuss/108084/C%2B%2B-4-lines-O\(m-\*-n\)-or-O\(1\)-and-KMP-O\(m-%2B-n\)-or-O\(n\)
1 parent bfa18e3 commit dbd0745

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed

Algorithms/0686.repeated-string-match/repeated-string-match.go

+27-9
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,33 @@
11
package problem0686
22

3-
import "strings"
4-
5-
func repeatedStringMatch(a string, b string) int {
6-
times := max(len(b)/len(a), 1)
7-
8-
if strings.Contains(strings.Repeat(a, times), b) {
9-
return times
3+
func repeatedStringMatch(A string, B string) int {
4+
// ref: https://leetcode.com/problems/repeated-string-match/discuss/108084/C%2B%2B-4-lines-O(m-*-n)-or-O(1)-and-KMP-O(m-%2B-n)-or-O(n)
5+
n, m := len(A), len(B)
6+
prefTable := make([]int, m+1)
7+
for sp, pp := 1, 0; sp < m; {
8+
if B[pp] == B[sp] {
9+
sp++
10+
pp++
11+
prefTable[sp] = pp
12+
} else if pp == 0 {
13+
sp++
14+
prefTable[sp] = pp
15+
} else {
16+
pp = prefTable[pp]
17+
}
1018
}
11-
if strings.Contains(strings.Repeat(a, times+1), b) {
12-
return times + 1
19+
20+
for i, j := 0, 0; i < n; i, j = i+max(1, j-prefTable[j]), prefTable[j] {
21+
for j < m && A[(i+j)%n] == B[j] {
22+
j++
23+
}
24+
if j == m {
25+
if (i+j)%n == 0 {
26+
return (i + j) / n
27+
} else {
28+
return (i+j)/n + 1
29+
}
30+
}
1331
}
1432
return -1
1533
}

Algorithms/0686.repeated-string-match/repeated-string-match_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ var tcs = []struct {
7979
2,
8080
},
8181

82+
{
83+
"abc",
84+
"cabcabca",
85+
4,
86+
},
8287
// 可以有多个 testcase
8388
}
8489

0 commit comments

Comments
 (0)