82
82
83
83
<!-- 这里可写通用的实现逻辑 -->
84
84
85
+ ** 方法一:模拟**
86
+
87
+ 根据题意模拟即可,注意,如果是最后一行,或者这一行只有一个单词,那么要左对齐,否则要均匀分配空格。
88
+
89
+ 时间复杂度 $O(L)$,空间复杂度 $O(L)$。其中 $L$ 为所有单词的长度之和。
90
+
85
91
<!-- tabs:start -->
86
92
87
93
### ** Python3**
91
97
``` python
92
98
class Solution :
93
99
def fullJustify (self , words : List[str ], maxWidth : int ) -> List[str ]:
94
- def partition (n , cnt ):
95
- res = []
96
- base, mod = divmod (n, cnt)
97
- i = j = 0
98
- while i < cnt:
99
- t = [' ' * base]
100
- if j < mod:
101
- t.append(' ' )
102
- res.append(' ' .join(t))
103
- i, j = i + 1 , j + 1
104
- return res
105
-
106
100
ans = []
107
101
i, n = 0 , len (words)
108
102
while i < n:
@@ -115,21 +109,18 @@ class Solution:
115
109
t.append(words[i])
116
110
i += 1
117
111
if i == n or len (t) == 1 :
118
- # this is the last line or only one word in a line
119
112
left = ' ' .join(t)
120
113
right = ' ' * (maxWidth - len (left))
121
114
ans.append(left + right)
122
- if i == n:
123
- break
124
115
continue
125
- words_width = cnt - len (t) + 1
126
- space_width = maxWidth - words_width
127
- spaces = partition(space_width, len (t) - 1 )
128
- sb = [t[ 0 ]]
129
- for j in range ( len (t) - 1 ):
130
- sb .append(spaces[j] )
131
- sb .append(t[j + 1 ])
132
- ans.append(' ' .join(sb ))
116
+ space_width = maxWidth - ( cnt - len (t) + 1 )
117
+ w, m = divmod (space_width, len (t) - 1 )
118
+ row = []
119
+ for j, s in enumerate (t[: - 1 ]):
120
+ row.append(s)
121
+ row .append(' ' * (w + ( 1 if j < m else 0 )) )
122
+ row .append(t[- 1 ])
123
+ ans.append(' ' .join(row ))
133
124
return ans
134
125
```
135
126
@@ -141,49 +132,31 @@ class Solution:
141
132
class Solution {
142
133
public List<String > fullJustify (String [] words , int maxWidth ) {
143
134
List<String > ans = new ArrayList<> ();
144
- int n = words. length;
145
- for (int i = 0 ; i < n;) {
135
+ for (int i = 0 , n = words. length; i < n;) {
146
136
List<String > t = new ArrayList<> ();
137
+ t. add(words[i]);
147
138
int cnt = words[i]. length();
148
- t . add(words[i ++ ]) ;
139
+ ++ i ;
149
140
while (i < n && cnt + 1 + words[i]. length() <= maxWidth) {
150
141
cnt += 1 + words[i]. length();
151
142
t. add(words[i++ ]);
152
143
}
153
144
if (i == n || t. size() == 1 ) {
154
- // this is the last line or only one word in a line
155
145
String left = String . join(" " , t);
156
146
String right = " " . repeat(maxWidth - left. length());
157
147
ans. add(left + right);
158
- if (i == n) {
159
- break ;
160
- }
161
148
continue ;
162
149
}
163
-
164
- int wordsWidth = cnt - t. size() + 1 ;
165
- int spaceWidth = maxWidth - wordsWidth;
166
- List<String > spaces = partition(spaceWidth, t. size() - 1 );
167
- StringBuilder sb = new StringBuilder (t. get(0 ));
150
+ int spaceWidth = maxWidth - (cnt - t. size() + 1 );
151
+ int w = spaceWidth / (t. size() - 1 );
152
+ int m = spaceWidth % (t. size() - 1 );
153
+ StringBuilder row = new StringBuilder ();
168
154
for (int j = 0 ; j < t. size() - 1 ; ++ j) {
169
- sb. append(spaces. get(j));
170
- sb. append(t. get(j + 1 ));
171
- }
172
- ans. add(sb. toString());
173
- }
174
- return ans;
175
- }
176
-
177
- private List<String > partition (int n , int cnt ) {
178
- List<String > ans = new ArrayList<> ();
179
- int base = n / cnt;
180
- int mod = n % cnt;
181
- for (int i = 0 , j = 0 ; i < cnt; ++ i, ++ j) {
182
- StringBuilder sb = new StringBuilder (" " . repeat(base));
183
- if (j < mod) {
184
- sb. append(' ' );
155
+ row. append(t. get(j));
156
+ row. append(" " . repeat(w + (j < m ? 1 : 0 )));
185
157
}
186
- ans. add(sb. toString());
158
+ row. append(t. get(t. size() - 1 ));
159
+ ans. add(row. toString());
187
160
}
188
161
return ans;
189
162
}
@@ -196,58 +169,43 @@ class Solution {
196
169
class Solution {
197
170
public:
198
171
vector<string > fullJustify(vector<string >& words, int maxWidth) {
199
- int n = words.size();
200
- vector<string > result;
201
- for (int i = 0; i < n; i++) {
202
- int begin = i;
203
- int wordLen = words[ i] .size();
204
- while (i + 1 < n && words[ i + 1] .size() + wordLen + 1 <= maxWidth) {
205
- wordLen += words[ ++i] .size() + 1;
206
- }
207
- int numberofWords = i - begin + 1;
208
- int space = 1;
209
- int extraSpace = 0;
210
- if (numberofWords > 1 && i < n - 1) {
211
- int remaining = maxWidth - wordLen;
212
- space = remaining / (numberofWords - 1) + 1;
213
- extraSpace = remaining % (numberofWords - 1);
172
+ vector<string > ans;
173
+ for (int i = 0, n = words.size(); i < n;) {
174
+ vector<string > t = {words[ i] };
175
+ int cnt = words[ i] .size();
176
+ ++i;
177
+ while (i < n && cnt + 1 + words[ i] .size() <= maxWidth) {
178
+ cnt += 1 + words[ i] .size();
179
+ t.emplace_back(words[ i++] );
214
180
}
215
- string line = words[ begin] ;
216
- for (int j = 1; j < numberofWords; j++) {
217
- line.append(space, ' ');
218
- if (j <= extraSpace) {
219
- line.push_back(' ');
181
+ if (i == n || t.size() == 1) {
182
+ string left = t[ 0] ;
183
+ for (int j = 1; j < t.size(); ++j) {
184
+ left += " " + t[ j] ;
220
185
}
221
- line += words[ begin + j] ;
186
+ string right = string(maxWidth - left.size(), ' ');
187
+ ans.emplace_back(left + right);
188
+ continue;
222
189
}
223
- if (line.size() < maxWidth) {
224
- line.append(maxWidth - line.size(), ' ');
190
+ int spaceWidth = maxWidth - (cnt - t.size() + 1);
191
+ int w = spaceWidth / (t.size() - 1);
192
+ int m = spaceWidth % (t.size() - 1);
193
+ string row;
194
+ for (int j = 0; j < t.size() - 1; ++j) {
195
+ row += t[ j] + string(w + (j < m ? 1 : 0), ' ');
225
196
}
226
- result.emplace_back(line);
197
+ row += t.back();
198
+ ans.emplace_back(row);
227
199
}
228
- return result ;
200
+ return ans ;
229
201
}
230
202
};
231
203
```
232
204
233
205
### **Go**
234
206
235
207
```go
236
- func fullJustify(words []string, maxWidth int) []string {
237
- partition := func(n, cnt int) []string {
238
- var res []string
239
- base, mod := n/cnt, n%cnt
240
- for i, j := 0, 0; i < cnt; i, j = i+1, j+1 {
241
- t := strings.Repeat(" ", base)
242
- if j < mod {
243
- t += " "
244
- }
245
- res = append(res, t)
246
- }
247
- return res
248
- }
249
-
250
- var ans []string
208
+ func fullJustify(words []string, maxWidth int) (ans []string) {
251
209
for i, n := 0, len(words); i < n; {
252
210
t := []string{words[i]}
253
211
cnt := len(words[i])
@@ -261,91 +219,93 @@ func fullJustify(words []string, maxWidth int) []string {
261
219
left := strings.Join(t, " ")
262
220
right := strings.Repeat(" ", maxWidth-len(left))
263
221
ans = append(ans, left+right)
264
- if i == n {
265
- break
266
- }
267
222
continue
268
223
}
269
- wordsWidth := cnt - len(t) + 1
270
- spaceWidth := maxWidth - wordsWidth
271
- spaces := partition(spaceWidth, len(t)-1)
272
- sb := t[0]
273
- for j := 0; j < len(t)-1; j++ {
274
- sb += spaces[j] + t[j+1]
224
+ spaceWidth := maxWidth - (cnt - len(t) + 1)
225
+ w := spaceWidth / (len(t) - 1)
226
+ m := spaceWidth % (len(t) - 1)
227
+ row := strings.Builder{}
228
+ for j, s := range t[:len(t)-1] {
229
+ row.WriteString(s)
230
+ row.WriteString(strings.Repeat(" ", w))
231
+ if j < m {
232
+ row.WriteString(" ")
233
+ }
275
234
}
276
- ans = append(ans, sb)
235
+ row.WriteString(t[len(t)-1])
236
+ ans = append(ans, row.String())
277
237
}
278
- return ans
238
+ return
239
+ }
240
+ ```
241
+
242
+ ### ** TypeScript**
243
+
244
+ ``` ts
245
+ function fullJustify(words : string [], maxWidth : number ): string [] {
246
+ const ans: string [] = [];
247
+ for (let i = 0 , n = words .length ; i < n ; ) {
248
+ const t: string [] = [words [i ]];
249
+ let cnt = words [i ++ ].length ;
250
+ while (i < n && cnt + 1 + words [i ].length <= maxWidth ) {
251
+ t .push (words [i ]);
252
+ cnt += 1 + words [i ++ ].length ;
253
+ }
254
+ if (i === n || t .length === 1 ) {
255
+ const left: string = t .join (' ' );
256
+ const right: string = ' ' .repeat (maxWidth - left .length );
257
+ ans .push (left + right );
258
+ continue ;
259
+ }
260
+ const spaceWidth: number = maxWidth - (cnt - t .length + 1 );
261
+ const w: number = Math .floor (spaceWidth / (t .length - 1 ));
262
+ const m: number = spaceWidth % (t .length - 1 );
263
+ const row: string [] = [];
264
+ for (let j = 0 ; j < t .length - 1 ; ++ j ) {
265
+ row .push (t [j ]);
266
+ row .push (' ' .repeat (w + (j < m ? 1 : 0 )));
267
+ }
268
+ row .push (t [t .length - 1 ]);
269
+ ans .push (row .join (' ' ));
270
+ }
271
+ return ans ;
279
272
}
280
273
```
281
274
282
275
### ** C#**
283
276
284
277
``` cs
285
- using System .Collections .Generic ;
286
- using System .Linq ;
287
- using System .Text ;
288
-
289
278
public class Solution {
290
279
public IList <string > FullJustify (string [] words , int maxWidth ) {
291
- var result = new List <string >();
292
- var buffer = new List <string >();
293
- var sb = new StringBuilder ();
294
- var len = 0 ;
295
-
296
- for (var i = 0 ; i < words .Length ; ++ i )
297
- {
298
- var newLen = words [i ].Length + (len == 0 ? 0 : len + 1 );
299
- if (newLen <= maxWidth )
300
- {
301
- buffer .Add (words [i ]);
302
- len = newLen ;
280
+ var ans = new List <string >();
281
+ for (int i = 0 , n = words .Length ; i < n ;) {
282
+ var t = new List <string >();
283
+ t .Add (words [i ]);
284
+ int cnt = words [i ].Length ;
285
+ ++ i ;
286
+ while (i < n && cnt + 1 + words [i ].Length <= maxWidth ) {
287
+ t .Add (words [i ]);
288
+ cnt += 1 + words [i ].Length ;
289
+ ++ i ;
303
290
}
304
- else
305
- {
306
- if (buffer .Count == 1 )
307
- {
308
- sb .Append (buffer [0 ]);
309
- sb .Append (' ' , maxWidth - buffer [0 ].Length );
310
- }
311
- else
312
- {
313
- var spaceCount = maxWidth - len + buffer .Count - 1 ;
314
- for (var j = 0 ; j < buffer .Count - 1 ; ++ j )
315
- {
316
- sb .Append (buffer [j ]);
317
- var spaceToAdd = (spaceCount - 1 ) / (buffer .Count - j - 1 ) + 1 ;
318
- sb .Append (' ' , spaceToAdd );
319
- spaceCount -= spaceToAdd ;
320
- }
321
- sb .Append (buffer .Last ());
322
- }
323
- result .Add (sb .ToString ());
324
- buffer .Clear ();
325
- buffer .Add (words [i ]);
326
- sb .Clear ();
327
- len = words [i ].Length ;
328
- }
329
- }
330
-
331
- if (buffer .Count > 0 )
332
- {
333
- for (var j = 0 ; j < buffer .Count ; ++ j )
334
- {
335
- if (sb .Length > 0 )
336
- {
337
- sb .Append (' ' );
338
- }
339
- sb .Append (buffer [j ]);
291
+ if (i == n || t .Count == 1 ) {
292
+ string left = string .Join (" " , t );
293
+ string right = new string (' ' , maxWidth - left .Length );
294
+ ans .Add (left + right );
295
+ continue ;
340
296
}
341
- if (sb .Length < maxWidth )
342
- {
343
- sb .Append (' ' , maxWidth - sb .Length );
297
+ int spaceWidth = maxWidth - (cnt - t .Count + 1 );
298
+ int w = spaceWidth / (t .Count - 1 );
299
+ int m = spaceWidth % (t .Count - 1 );
300
+ var row = new StringBuilder ();
301
+ for (int j = 0 ; j < t .Count - 1 ; ++ j ) {
302
+ row .Append (t [j ]);
303
+ row .Append (new string (' ' , w + (j < m ? 1 : 0 )));
344
304
}
345
- result .Add (sb .ToString ());
305
+ row .Append (t [t .Count - 1 ]);
306
+ ans .Add (row .ToString ());
346
307
}
347
-
348
- return result ;
308
+ return ans ;
349
309
}
350
310
}
351
311
```
0 commit comments