Word Wrap with Even Justification
Problem statement
Format a sequence of words into fixed-width lines. Any run of whitespace separates words, except that whitespace immediately around a hyphen is ignored, so go - to becomes go-to.
Pack words greedily using one space while deciding what fits. Every returned line must then have exactly width characters. For a line with multiple words, distribute as many spaces as possible equally between every adjacent pair and append any remainder to the end. Center a one-word line, placing an unmatched extra space at the end.
Keep a hyphenated word intact when its normalized form fits within width. When it is longer than width, repeatedly split at the rightmost hyphen whose left piece, including that hyphen, fits; treat the pieces as consecutive words.
Function
justifyWords(text: String, width: int) → String[]Examples
Example 1
text = "a cat is an animal"width = 6return = ["a cat","is an","animal"]After greedy packing, final justification gives both two-word lines six characters.
Example 2
text = "cat is an animal and so is a dog"width = 12return = ["cat is an ","animal and","so is a dog "]The first line has two spaces per gap and one leftover space at the end.
Example 3
text = "auto-complete is my go - to"width = 8return = [" auto- ","complete","is my"," go-to "]The long hyphenated word splits after auto-, while whitespace around the hyphen in go - to is ignored.
Constraints
1 <= text.length <= 100000.1 <= width <= 200.- The input contains printable ASCII characters and whitespace; non-whitespace text consists of letters and hyphens.
- After normalizing whitespace around hyphens, every ordinary word and every segment between allowed hyphen splits fits within
width.