@@ -12,18 +12,20 @@ func shortestSuperstring(A []string) string {
12
12
res := strings .Repeat ("?" , 12 * 20 + 1 )
13
13
for i := 0 ; i < size ; i ++ {
14
14
isUsed [i ] = true
15
- greedy (append (indexs , i ), A , isUsed , suffixes , & res )
15
+ greedy (append (indexs , i ), len ( A [ i ]), A , isUsed , suffixes , & res )
16
16
isUsed [i ] = false
17
17
}
18
18
return res
19
19
}
20
20
21
+ // indexs 按顺序记录了 super string 中单词的 index
22
+ // length 记录了 super string 的长度
21
23
// 传入 suffixes 是为了避免重复多次计算两个单词之间的重叠关系
22
- func greedy (indexs []int , A []string , isUsed []bool , suffixes [][]int , minRes * string ) {
24
+ func greedy (indexs []int , length int , A []string , isUsed []bool , suffixes [][]int , minRes * string ) {
23
25
if len (indexs ) == len (A ) {
24
- tmp := connect ( A , indexs , suffixes )
25
- if len ( * minRes ) > len ( tmp ) {
26
- * minRes = tmp
26
+ if len ( * minRes ) > length {
27
+ // NOTICE: 只有在确定找到了更短的 super string 时,才把它拼接出来。
28
+ * minRes = connect ( A , indexs , suffixes )
27
29
}
28
30
return
29
31
}
@@ -33,10 +35,10 @@ func greedy(indexs []int, A []string, isUsed []bool, suffixes [][]int, minRes *s
33
35
maxLen := - 1
34
36
lens := suffixes [tail ]
35
37
for i , sl := range lens {
36
- if isUsed [i ] {
38
+ if maxLen >= sl || isUsed [i ] {
37
39
continue
38
40
}
39
- maxLen = max ( maxLen , sl )
41
+ maxLen = sl
40
42
}
41
43
42
44
// only connect string with max suffix length
@@ -45,7 +47,7 @@ func greedy(indexs []int, A []string, isUsed []bool, suffixes [][]int, minRes *s
45
47
continue
46
48
}
47
49
isUsed [i ] = true
48
- greedy (append (indexs , i ), A , isUsed , suffixes , minRes )
50
+ greedy (append (indexs , i ), length + len ( A [ i ]) - maxLen , A , isUsed , suffixes , minRes )
49
51
isUsed [i ] = false
50
52
}
51
53
}
@@ -83,20 +85,13 @@ func connect(A []string, indexs []int, suffixes [][]int) string {
83
85
sb .WriteString (A [i ])
84
86
for k := 1 ; k < size ; k ++ {
85
87
j := indexs [k ]
86
- sl := suffixes [i ][j ]
87
- sb .WriteString (A [j ][sl :])
88
+ s := suffixes [i ][j ]
89
+ sb .WriteString (A [j ][s :])
88
90
i = j
89
91
}
90
92
return sb .String ()
91
93
}
92
94
93
- func max (a , b int ) int {
94
- if a > b {
95
- return a
96
- }
97
- return b
98
- }
99
-
100
95
func min (a , b int ) int {
101
96
if a < b {
102
97
return a
0 commit comments