-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs.go
52 lines (47 loc) · 1.05 KB
/
lcs.go
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
41
42
43
44
45
46
47
48
49
50
51
52
package json_diff
import (
"github.com/520MianXiangDuiXiang520/json-diff/decode"
)
func max(a, b int) int {
if a < b {
return b
}
return a
}
func longestCommonSubsequence(first, second []*decode.JsonNode) []*decode.JsonNode {
line := len(first) + 1
column := len(second) + 1
if line == 1 || column == 1 {
return make([]*decode.JsonNode, 0)
}
dp := make([][]int, line)
for i := 0; i < line; i++ {
dp[i] = make([]int, column)
}
for i := 1; i < line; i++ {
for j := 1; j < column; j++ {
if first[i-1].Equal(second[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
start, end := len(first), len(second)
cur := dp[start][end] - 1
res := make([]*decode.JsonNode, cur+1)
// fix issue #5 (https://github.com/520MianXiangDuiXiang520/json-diff/issues/5)
for cur >= 0 {
if end > 0 && dp[start][end] == dp[start][end-1] {
end--
} else if start > 0 && dp[start][end] == dp[start-1][end] {
start--
} else {
res[cur] = first[start-1]
start--
end--
cur--
}
}
return res
}