Reflow Text with Unpadded Singletons
Problem statement
Flatten the words from the strings in text, preserving their order, and reflow them into lines of maximum width width. Never split a word. Select the largest consecutive group of words that fits when separated by one space.
Distribute ASCII spaces between words as evenly as possible to reach the width on each fully justified line. Gap lengths may differ by at most one; put any extra separator characters in the leftmost gaps.
Fully justify every line with two or more words, including the final line. A one-word line is returned unchanged without padding.
For this exercise, assume input contains only English letters and ASCII spaces. Ignore leading, trailing and repeated spaces inside source strings; source-string boundaries act as whitespace. An empty input or input without words returns an empty array.
Function
justifyText(text: String[], width: int) → String[]Examples
Example 1
text = ["Some modern typesetting programs","offer four justification","options"]width = 24return = ["Some modern typesetting","programs offer four","justification options"]The complete first source fixture is preserved; its final multiword line is fully justified.
Example 2
text = ["The Earth is","the only world","known so far","to harbor life"]width = 18return = ["The Earth is the","only world known","so far to harbor","life"]The complete second source fixture is preserved, including its unpadded final singleton.
Example 3
text = ["It underscores our responsibility","to deal more kindly with one another"]width = 15return = ["It underscores","our","responsibility","to deal more","kindly with one","another"]The complete third source fixture preserves two nonfinal unpadded singletons and the final singleton.
Constraints
- For this exercise, assume
0 <= text.length <= 100and the total number of input characters is at most2000. - For this exercise, assume
1 <= width <= 100, and every nonempty word has length at most width. - Each input string contains only uppercase or lowercase English letters and ASCII spaces.