Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 5a41d25

Browse files
committed
943 finish
1 parent 9da19c2 commit 5a41d25

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

Algorithms/0943.find-the-shortest-superstring/find-the-shortest-superstring.go

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,20 @@ func shortestSuperstring(A []string) string {
1212
res := strings.Repeat("?", 12*20+1)
1313
for i := 0; i < size; i++ {
1414
isUsed[i] = true
15-
greedy(append(indexs, i), A, isUsed, suffixes, &res)
15+
greedy(append(indexs, i), len(A[i]), A, isUsed, suffixes, &res)
1616
isUsed[i] = false
1717
}
1818
return res
1919
}
2020

21+
// indexs 按顺序记录了 super string 中单词的 index
22+
// length 记录了 super string 的长度
2123
// 传入 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) {
2325
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)
2729
}
2830
return
2931
}
@@ -33,10 +35,10 @@ func greedy(indexs []int, A []string, isUsed []bool, suffixes [][]int, minRes *s
3335
maxLen := -1
3436
lens := suffixes[tail]
3537
for i, sl := range lens {
36-
if isUsed[i] {
38+
if maxLen >= sl || isUsed[i] {
3739
continue
3840
}
39-
maxLen = max(maxLen, sl)
41+
maxLen = sl
4042
}
4143

4244
// only connect string with max suffix length
@@ -45,7 +47,7 @@ func greedy(indexs []int, A []string, isUsed []bool, suffixes [][]int, minRes *s
4547
continue
4648
}
4749
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)
4951
isUsed[i] = false
5052
}
5153
}
@@ -83,20 +85,13 @@ func connect(A []string, indexs []int, suffixes [][]int) string {
8385
sb.WriteString(A[i])
8486
for k := 1; k < size; k++ {
8587
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:])
8890
i = j
8991
}
9092
return sb.String()
9193
}
9294

93-
func max(a, b int) int {
94-
if a > b {
95-
return a
96-
}
97-
return b
98-
}
99-
10095
func min(a, b int) int {
10196
if a < b {
10297
return a

0 commit comments

Comments
 (0)