1
1
package Problem0068
2
2
3
+ import "strings"
4
+
3
5
func fullJustify (words []string , maxWidth int ) []string {
4
6
res := []string {}
5
7
temp := []string {}
6
8
width := 0
9
+ isLast := false
7
10
8
11
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 ))
11
14
}
12
15
13
16
return res
14
17
}
15
18
16
- // 返回待组合的单词,需要组合的单词,和这些单词的长度之和
17
- func split (words []string , maxWidth int ) ([]string , []string , int ) {
19
+ // 返回待组合的单词,需要组合的单词,和这些单词的长度之和, 是否是结尾
20
+ func split (words []string , maxWidth int ) ([]string , []string , int , bool ) {
18
21
res := make ([]string , 1 )
19
22
res [0 ] = words [0 ]
20
23
width := len (words [0 ])
24
+
21
25
i := 1
22
26
for ; i < len (words ); i ++ {
23
- if width + len (words [i ]) > maxWidth {
27
+ if width + len (res ) + len ( words [i ]) > maxWidth {
24
28
break
25
29
}
26
30
res = append (res , words [i ])
27
31
width += len (words [i ])
28
32
}
29
- return words [i :], res , width
33
+
34
+ return words [i :], res , width , i == len (words )
30
35
}
31
36
32
- func combine (words []string , width , maxWidth int ) string {
37
+ func combine (words []string , width , maxWidth int , isLast bool ) string {
33
38
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 )
35
44
36
45
res := ""
37
46
for i , v := range spaces {
38
47
res += words [i ] + v
39
48
}
40
- res += words [wordCount - 1 ]
49
+ if wordCount > 1 {
50
+ res += words [wordCount - 1 ]
51
+ }
41
52
42
53
return res
43
54
}
@@ -50,3 +61,13 @@ func makeSpaces(Len, count int) []string {
50
61
51
62
return res
52
63
}
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
+ }
0 commit comments