Wrap Words into Hyphen-Separated Lines
Problem statement
Given ordered words and maxLen, wrap the words into lines. Keep every word intact and preserve the input order.
Each line contains the largest consecutive group that fits within maxLen when joined with exactly one hyphen between words. If adding the next word and its preceding hyphen would exceed maxLen, start a new line with that word.
For this exercise, assume words are nonempty English-letter strings and each word individually fits. Preserve casing and repeated occurrences. Add no trailing hyphen or padding. Empty input returns an empty array.
Function
wrapWords(words: String[], maxLen: int) → String[]Examples
Example 1
words = ["Hello","Sir","Please","Upvote","If","You","Like","My","Post"]maxLen = 10return = ["Hello-Sir","Please","Upvote-If","You-Like","My-Post"]The complete original source input and all five output lines are preserved.
Example 2
words = ["a","b","c"]maxLen = 3return = ["a-b","c"]This authored example accepts an exactly fitting first line and preserves the last word.
Example 3
words = ["Abcd","e"]maxLen = 4return = ["Abcd","e"]This authored example shows that lines are not padded or split.
Constraints
- For this exercise, assume
0 <= words.length <= 200and1 <= maxLen <= 100. - Each word contains only uppercase or lowercase English letters and has length from 1 through maxLen.