-
Notifications
You must be signed in to change notification settings - Fork 2
/
lcs.go2
73 lines (61 loc) · 1.17 KB
/
lcs.go2
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
// vim:set ft=go:
// snip ------------------------------------------------------------------------
// Longest Common Subsequence
func LCS[T comparable](s1, s2 []T) int {
n := len(s1)
m := len(s2)
dp := lcs_dp(s1, s2)
return dp[n][m]
}
// Longest Common Subsequence with Reconstruction
func LCSR[T comparable](s1, s2 []T) []T {
n := len(s1)
m := len(s2)
dp := lcs_dp(s1, s2)
var res []T
i, j := n, m
for 0 < i && 0 < j {
for 0 < i && dp[i-1][j] == dp[i][j] {
i--
}
if i == 0 {
break
}
for 0 < j && dp[i][j-1] == dp[i][j] {
j--
}
if j == 0 {
break
}
res = append(res, s1[i-1])
i--
j--
}
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}
func lcs_dp[T comparable](s1, s2 []T) [][]int {
n := len(s1)
m := len(s2)
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 0; i <= n; i++ {
for j := 0; j <= m; j++ {
if 0 < i {
dp[i][j] = max(dp[i][j], dp[i-1][j])
}
if 0 < j {
dp[i][j] = max(dp[i][j], dp[i][j-1])
}
if 0 < i && 0 < j && s1[i-1] == s2[j-1] {
dp[i][j] = max(dp[i][j], dp[i-1][j-1]+1)
}
}
}
return dp
}