Count Lines in a Width-Limited Document
Problem statement
Given document text text and a maximum line width maxWidth, return the number of display lines produced by greedy word wrapping.
- Every character has width one.
- Spaces and tabs separate words. Consecutive horizontal whitespace is displayed as one space, and leading or trailing horizontal whitespace is ignored.
- A newline starts a new paragraph. Every empty paragraph contributes one blank display line.
- Within each non-empty paragraph, place as many words as possible on each line with one display space between adjacent words.
- If a word is longer than
maxWidth, first move it to a new line when the current line is non-empty, then split it into consecutive width-maxWidthchunks. Its final shorter chunk may share a line with the next word under the ordinary one-space rule.
Empty text contains zero display lines.
Function
countWrappedLines(text: String, maxWidth: int) → intExamples
Example 1
text = "Google builds\nfast tools"maxWidth = 10return = 3The first paragraph wraps into Google and builds. The second paragraph fits as fast tools.
Example 2
text = "abcdef x"maxWidth = 3return = 3The oversized word becomes abc and def; x needs a third line.
Example 3
text = "\n"maxWidth = 5return = 2One newline separates two empty paragraphs, and each contributes one blank line.
Constraints
0 <= text.length <= 200000.1 <= maxWidth <= 100000.textcontains printable characters, spaces, tabs, and newline characters.