You are given an array of strings words (each string is a word with no spaces) and an integer maxWidth.
Return a list of lines (strings) that formats the words into lines of exactly maxWidth characters each.
Rules
-
Greedy packing:
Build lines from left to right using as many words as possible per line (without exceeding
maxWidth
).
-
Do not split words:
A word must appear entirely on one line.
-
Space distribution (non-last lines):
-
Suppose a line contains
k
words.
-
There are
k-1
mandatory gaps
between
adjacent words; each such gap must have
at least 1 space
.
-
After placing those mandatory spaces, distribute any
remaining spaces
as evenly as possible across
all
k+1 gaps
:
-
the gap
before the first word
(leading spaces),
-
the
k-1
gaps
between words
,
-
the gap
after the last word
(trailing spaces).
-
If the spaces cannot be distributed evenly, assign the extra one-by-one starting from the
leftmost gap
(leading gap first, then left-to-right).
-
This means a line
may start and/or end with spaces
.
-
Last line:
Left-justify it: use a single space between words and put all remaining spaces at the
end
of the line.
Input / Output
-
Input:
words: string[]
,
maxWidth: int
-
Output:
string[]
where each string has length exactly
maxWidth
.
Example
If words = ["a","b","c"] and maxWidth = 5:
-
All three words fit on one line as the last line:
"a b c"
has length 5, so output is
["a b c"]
.
Constraints
-
1 <= words.length <= 300
-
1 <= len(words[i]) <= maxWidth <= 100
-
words[i]
contains no spaces.