Accumulate character widths, starting a new line whenever the next character would exceed one hundred units.
Complexity
O(n) time and O(1) extra space.
Compute the number of bounded-width lines needed for a string and the final line's width.
Accumulate character widths, starting a new line whenever the next character would exceed one hundred units.
O(n) time and O(1) extra space.
package main
func numberOfLines(widths []int, s string) []int {
lines, width := 1, 0
for _, character := range s {
next := widths[character-'a']
if width+next > 100 {
lines++
width = next
} else {
width += next
}
}
return []int{lines, width}
}
class Solution:
def numberOfLines(self, widths: list[int], s: str) -> list[int]:
lines, width = 1, 0
for character in s:
next_width = widths[ord(character) - ord("a")]
if width + next_width > 100: lines, width = lines + 1, next_width
else: width += next_width
return [lines, width]
function numberOfLines(widths: number[], s: string): number[] {
let lines = 1;
let width = 0;
for (const character of s) { const next = widths[character.charCodeAt(0) - 97]; if (width + next > 100) { lines += 1; width = next; } else width += next; }
return [lines, width];
}