Problem
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
Note:
- A word is defined as a character sequence consisting of non-space characters only.
- Each word’s length is guaranteed to be greater than 0 and not exceed maxWidth.
- The input array
words
contains at least one word.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation
-
First, we need to find out how many words can fit in one line, in other word, where does the line break. For example, if words[0, i] can fits in the current line, and has total word length
curLen
. Besides the words length, it also needs to add the space length, if words[0, i] can fit in this line, then there arei
space, socurLen = curLen + i
. The line break will have the conditioncurLen + 1 + words[i+1].length() > maxWidth
. -
After we know how many words in the current line, then we need to find out how many spaces between the words. We can find out how many space left
maxWidth - curLen = blankNum
,curLen
is the total words length plus one space length between these words, then we divide it with the space number,blankNum / (numOfWord - 1) = base
, each space will addbase
more length, and if there are some space leftrest
,blankNum % (numOfWord - 1) = rest
then the firstrest
space will have one more length. -
The special case is the last line, it has one space between the words, and all the rest of space will be filled at the end.
Solution
1 |
|