
Sponsored
Sponsored
In this approach, we iterate over the string and keep track of the width of the current line. When adding another character exceeds the allowed line width of 100 pixels, we start a new line. We store the total number of lines and the width of the last line.
The time complexity of this approach is O(n), where s. The space complexity is O(1), as we are only using a fixed amount of extra space.
1#include <stdio.h>
2
3void numberOfLines(int* widths, int widthsSize, char* s, int* result) {
4 int currentWidth = 0;
5 int totalLines = 1; // Start with the first line
6
7 for (int i = 0; s[i] != '\0'; ++i) {
8 int charWidth = widths[s[i] - 'a'];
9 if (currentWidth + charWidth > 100) {
10 totalLines++;
11 currentWidth = 0;
12 }
13 currentWidth += charWidth;
14 }
15
16 result[0] = totalLines;
17 result[1] = currentWidth;
18}
19
20int main() {
21 int widths[26] = {4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
22 char s[] = "bbbcccdddaaa";
23 int result[2];
24 numberOfLines(widths, 26, s, result);
25 printf("[%d, %d]\n", result[0], result[1]);
26 return 0;
27}
28We start by initializing totalLines to 1 and currentWidth to 0. As we iterate through each character in the string s, we fetch its corresponding width from the widths array. If adding a character would make the current line exceed 100 pixels, we increment the totalLines and reset currentWidth. Otherwise, we add the character's width to currentWidth.
This approach takes the prefix summed widths of the string. For each new position, the difference between the prefix sums represents the total width of characters up to that position. Using this information, we determine how many characters fit into each line under the given constraints, thereby expanding calculation efficiency.
The time complexity is O(n) for constructing the prefix sum and iterating through it. The space complexity is O(n) due to the prefix sum array.
1
Java implements prefix sums to monitor cumulative character widths. The iterative loop inspects when cumulative differences surpass 100 pixels, thereby adjusting totalLines and updating lastValid positions for new line starts.