Skip to content

Commit 860eb21

Browse files
committed
add solution for maximum-length-of-repeated-subarray
1 parent 7ad2c39 commit 860eb21

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package leetcode
2+
3+
func findLength(A []int, B []int) int {
4+
rec := make([][]int, len(A)+1)
5+
for i := 0; i < len(A)+1; i++ {
6+
rec[i] = make([]int, len(B)+1)
7+
}
8+
9+
max := 0
10+
endA := len(A) - 1
11+
endB := len(B) - 1
12+
for i := endA; i >= 0; i-- {
13+
for j := endB; j >= 0; j-- {
14+
if B[j] == A[i] {
15+
rec[i][j] = rec[i+1][j+1] + 1
16+
if rec[i][j] > max {
17+
max = rec[i][j]
18+
}
19+
}
20+
}
21+
}
22+
return max
23+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package leetcode
2+
3+
import "testing"
4+
5+
func TestFindLength(t *testing.T) {
6+
tests := []struct {
7+
a []int
8+
b []int
9+
expect int
10+
}{
11+
{
12+
a: []int{1, 2, 3, 2, 1},
13+
b: []int{3, 2, 1, 4, 7},
14+
expect: 3,
15+
}, {
16+
a: []int{1, 4, 7, 2, 1},
17+
b: []int{3, 2, 1, 4, 7},
18+
expect: 3,
19+
}, {
20+
a: []int{1},
21+
b: []int{2},
22+
expect: 0,
23+
}, {
24+
a: []int{2},
25+
b: []int{2},
26+
expect: 1,
27+
},
28+
}
29+
30+
for i, item := range tests {
31+
actual := findLength(item.a, item.b)
32+
if actual != item.expect {
33+
t.Fatalf("%d expect %d, actual %d\n", i, item.expect, actual)
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)