Skip to content

Commit bd4db64

Browse files
aQuaaQua
aQua
authored and
aQua
committed
68 runtime error: 除数为零
1 parent c1eebec commit bd4db64

File tree

2 files changed

+56
-8
lines changed

2 files changed

+56
-8
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,52 @@
11
package Problem0068
22

33
func fullJustify(words []string, maxWidth int) []string {
4+
res := []string{}
5+
temp := []string{}
6+
width := 0
47

8+
for len(words) > 0 {
9+
words, temp, width = split(words, maxWidth)
10+
res = append(res, combine(temp, width, maxWidth))
11+
}
12+
13+
return res
14+
}
15+
16+
// 返回待组合的单词,需要组合的单词,和这些单词的长度之和
17+
func split(words []string, maxWidth int) ([]string, []string, int) {
18+
res := make([]string, 1)
19+
res[0] = words[0]
20+
width := len(words[0])
21+
i := 1
22+
for ; i < len(words); i++ {
23+
if width+len(words[i]) > maxWidth {
24+
break
25+
}
26+
res = append(res, words[i])
27+
width += len(words[i])
28+
}
29+
return words[i:], res, width
30+
}
31+
32+
func combine(words []string, width, maxWidth int) string {
33+
wordCount := len(words)
34+
spaces := makeSpaces(wordCount-1, maxWidth-width)
35+
36+
res := ""
37+
for i, v := range spaces {
38+
res += words[i] + v
39+
}
40+
res += words[wordCount-1]
41+
42+
return res
43+
}
44+
45+
func makeSpaces(Len, count int) []string {
46+
res := make([]string, Len)
47+
for i := 0; i < count; i++ {
48+
res[i%Len] += " "
49+
}
50+
51+
return res
552
}
Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0068
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -14,13 +14,13 @@ type question struct {
1414

1515
// para 是参数
1616
type para struct {
17-
words []string
18-
maxWidth int
17+
words []string
18+
maxWidth int
1919
}
2020

2121
// ans 是答案
2222
type ans struct {
23-
one []string
23+
one []string
2424
}
2525

2626
func Test_Problem0068(t *testing.T) {
@@ -30,20 +30,21 @@ func Test_Problem0068(t *testing.T) {
3030

3131
question{
3232
para{
33-
,
33+
[]string{"This", "is", "an", "example", "of", "text", "justification."},
34+
16,
3435
},
3536
ans{
36-
,
37+
[]string{"This is an", "example of text", "justification. "},
3738
},
3839
},
39-
40+
4041
// 如需多个测试,可以复制上方元素。
4142
}
4243

4344
for _, q := range qs {
4445
a, p := q.ans, q.para
4546
fmt.Printf("~~%v~~\n", p)
4647

47-
ast.Equal(a.one, fullJustify(p. ), "输入:%v", p)
48+
ast.Equal(a.one, fullJustify(p.words, p.maxWidth), "输入:%v", p)
4849
}
4950
}

0 commit comments

Comments
 (0)