Skip to content

Commit 5bd60f1

Browse files
aQuaaQua
aQua
authored and
aQua
committed
68 accepted
1 parent bd4db64 commit 5bd60f1

File tree

2 files changed

+39
-9
lines changed

2 files changed

+39
-9
lines changed
Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,54 @@
11
package Problem0068
22

3+
import "strings"
4+
35
func fullJustify(words []string, maxWidth int) []string {
46
res := []string{}
57
temp := []string{}
68
width := 0
9+
isLast := false
710

811
for len(words) > 0 {
9-
words, temp, width = split(words, maxWidth)
10-
res = append(res, combine(temp, width, maxWidth))
12+
words, temp, width, isLast = split(words, maxWidth)
13+
res = append(res, combine(temp, width, maxWidth, isLast))
1114
}
1215

1316
return res
1417
}
1518

16-
// 返回待组合的单词,需要组合的单词,和这些单词的长度之和
17-
func split(words []string, maxWidth int) ([]string, []string, int) {
19+
// 返回待组合的单词,需要组合的单词,和这些单词的长度之和, 是否是结尾
20+
func split(words []string, maxWidth int) ([]string, []string, int, bool) {
1821
res := make([]string, 1)
1922
res[0] = words[0]
2023
width := len(words[0])
24+
2125
i := 1
2226
for ; i < len(words); i++ {
23-
if width+len(words[i]) > maxWidth {
27+
if width+len(res)+len(words[i]) > maxWidth {
2428
break
2529
}
2630
res = append(res, words[i])
2731
width += len(words[i])
2832
}
29-
return words[i:], res, width
33+
34+
return words[i:], res, width, i == len(words)
3035
}
3136

32-
func combine(words []string, width, maxWidth int) string {
37+
func combine(words []string, width, maxWidth int, isLast bool) string {
3338
wordCount := len(words)
34-
spaces := makeSpaces(wordCount-1, maxWidth-width)
39+
if wordCount == 1 || isLast {
40+
return combineSpecial(words, maxWidth)
41+
}
42+
spaceCount := wordCount - 1
43+
spaces := makeSpaces(spaceCount, maxWidth-width)
3544

3645
res := ""
3746
for i, v := range spaces {
3847
res += words[i] + v
3948
}
40-
res += words[wordCount-1]
49+
if wordCount > 1 {
50+
res += words[wordCount-1]
51+
}
4152

4253
return res
4354
}
@@ -50,3 +61,13 @@ func makeSpaces(Len, count int) []string {
5061

5162
return res
5263
}
64+
65+
func combineSpecial(words []string, maxWidth int) string {
66+
res := strings.Join(words, " ")
67+
68+
for len(res) < maxWidth {
69+
res += " "
70+
}
71+
72+
return res
73+
}

Algorithms/0068.text-justification/text-justification_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ func Test_Problem0068(t *testing.T) {
3838
},
3939
},
4040

41+
question{
42+
para{
43+
[]string{"What", "must", "be", "shall", "be."},
44+
12,
45+
},
46+
ans{
47+
[]string{"What must be", "shall be. "},
48+
},
49+
},
4150
// 如需多个测试,可以复制上方元素。
4251
}
4352

0 commit comments

Comments
 (0)