-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs.go
52 lines (49 loc) · 1.03 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
func max(a, b int) int {
if a < b {
return b
}
return a
}
func longestCommonSubsequence(first, second []*JsonNode) []*JsonNode {
line := len(first) + 1
column := len(second) + 1
if line == 1 || column == 1 {
return make([]*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])
}
}
}
// printDP(dp)
start, end := len(first), len(second)
cur := dp[start][end] - 1
res := make([]*JsonNode, cur+1)
for cur >= 0 {
if end >= 0 && start >= 0 &&
dp[start][end] == dp[start][end-1] &&
dp[start][end] == dp[start-1][end] {
start--
end--
} else 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]
cur--
start--
end--
}
}
return res
}