Document Line Wrap
GoogleOnsiteEasy
You are given the text of a document as a string text and a page width width in characters. The text holds words separated by spaces and "\n" characters.
Part 1: Count wrapped rows
Lay the text out one row at a time and return the number of rows it takes on a page width characters wide.
A row holds words separated by exactly one space and is at most width characters wide, counting those spaces. A run of several spaces counts as one separator. Words are never split, and wrapping is greedy: a word goes on the current row if it fits after one space, otherwise it starts a new row.
Each "\n" ends the current row, even if that row is empty, so the pieces of text between newlines are laid out separately. A piece with no words, such as the one between two newlines or after a final newline, still takes one row. The empty string takes 0 rows.
- Example 1
- text
"Hello world\nFoo bar baz qux"- width
10- Output
4
Why:
Hello worldis 11 characters, too wide for one row, so it wraps to two rows.Foo bar baz quxfitsFoo barand thenbaz qux, two more rows. Total 4. - Example 2
- text
"a\n\n\nb"- width
5- Output
4
Why: The text has four lines:
a, two empty lines andb. Each line takes one row, including the empty ones.
Constraints
0 <= len(text) <= 10^5textcontains only letters, spaces and"\n"characters1 <= width <= 1001 <= len(word) <= widthfor every word intext