# 806. Number of Lines To Write String¶

• Time: $O(n)$
• Space: $O(1)$
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { public: vector numberOfLines(vector& widths, string s) { int numLines = 1; int runningWidth = 0; for (const char c : s) { const int width = widths[c - 'a']; if (runningWidth + width <= 100) { runningWidth += width; } else { ++numLines; runningWidth = width; } } return {numLines, runningWidth}; } };
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public int[] numberOfLines(int[] widths, String s) { int numLines = 1; int runningWidth = 0; for (final char c : s.toCharArray()) { final int width = widths[c - 'a']; if (runningWidth + width <= 100) { runningWidth += width; } else { ++numLines; runningWidth = width; } } return new int[] {numLines, runningWidth}; } }
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: numLines = 1 runningWidth = 0 for c in s: width = widths[ord(c) - ord('a')] if runningWidth + width <= 100: runningWidth += width else: numLines += 1 runningWidth = width return [numLines, runningWidth]