Justify Text to a Fixed Width
Problem statement
Arrange the ordered array words into lines of exactly width characters. For this exercise, assume every word is nonempty, contains lowercase English letters and fits within the width. Keep the words in input order and never split a word.
For this exercise, assume each line takes the longest next prefix of words that fits when at least one ASCII space separates neighboring words. Every nonfinal line containing two or more words distributes all its spaces as evenly as possible among its internal gaps. When the space count does not divide evenly, earlier gaps receive the extra spaces.
For this exercise, assume the final line and every singleton line are left aligned: use one space between words and add spaces at the end until the line reaches the width. Return the lines as a string array. Trailing spaces are part of each returned string.
For this exercise, assume empty input returns an empty array. Do not modify the input words.
Function
justifyText(words: String[], width: int) → String[]Examples
Example 1
words = ["this","is","text","justified"]width = 16return = ["this is text","justified "]Authored example: The first line has six spaces across two gaps: this followed by three spaces, is, three spaces and text. The final nine-letter word receives seven trailing spaces.
Example 2
words = ["a","b","c","d"]width = 3return = ["a b","c d"]Authored example: Each greedy line holds two words. Both returned strings have length three.
Example 3
words = ["word"]width = 8return = ["word "]Authored example: The returned word has four trailing spaces; those spaces are part of the result.
Constraints
- For this exercise, assume
0 <= words.length <= 100. - For this exercise, assume
1 <= width <= 80. - Each word has from
1through20lowercase English letters and length at mostwidth.