Fully Justify Lines of Words
Problem statement
Format words into lines of exactly maxWidth characters. Keep the words in order, and greedily place as many words as fit on each line when consecutive words need at least one separating space.
For a non-final line with at least two words, distribute the spaces between words as evenly as possible. When they do not divide evenly, the leftmost gaps receive one more space than the remaining gaps.
Left-justify the final line and every single-word line: use one space between words and put all remaining spaces at the right end. Return the lines as an array of strings. Trailing spaces are part of the answer and must be preserved.
Function
justifyText(words: String[], maxWidth: int) → String[]Examples
Example 1
words = ["This","is","a","sample","text"]maxWidth = 12return = ["This is a","sample text "]The first line holds This, is, and a, with seven word characters. Its five spaces split into gaps of three and two. The final line uses one space between sample and text and one trailing space. Both lines have length 12.
Example 2
words = ["a","b","c","dddd"]maxWidth = 6return = ["a b c","dddd "]The first three words fit on the first line. Three spaces split into gaps of two and one. The final word dddd receives two trailing spaces.
Constraints
1 <= words.length <= 300.- Each word has 1 to 20 characters.
1 <= maxWidth <= 100.- No word is longer than maxWidth.
- Words contain only non-space printable ASCII characters, with codes 33 through 126.