68 Text Justification
Given an array of words and a length L, format the text such that each line has exactly L 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 L 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.
For example,
words:["This", "is", "an", "example", "of", "text", "justification."]
L:16
.
Return the formatted lines as:
Note:Each word is guaranteed not to exceed L in length.
The Idea: Keep two arrays: one that temporarily fills a list of words that can fit, and another final array solution. Append to the temporary array until it reaches maximum capacity. Then do a round robin kind of traversal through this array until every the amount of spaces full occupy the maximum width as required. Then dump the information into the final array, and reset.
Complexity: O(n + k) where n is the total number of words, and k is the average amount of spaces we justify in a given text. O(n) extra space.
Discussion
What if we allow words to be longer than the width of the line?
Then
len(w)
would need to be removed from the check.
Last updated