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.
#include <string>
#include <iostream>
using namespace std;
vector<int> numberOfLines(vector<int>& widths, string s) {
int totalLines = 1;
int currentWidth = 0;
for (char c : s) {
int charWidth = widths[c - 'a'];
if (currentWidth + charWidth > 100) {
totalLines++;
currentWidth = charWidth;
} else {
currentWidth += charWidth;
}
}
return {totalLines, currentWidth};
}
int main() {
vector<int> widths = {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};
string s = "bbbcccdddaaa";
vector<int> result = numberOfLines(widths, s);
cout << "[" << result[0] << ", " << result[1] << "]" << endl;
return 0;
}
The C++ implementation similarly increments totalLines
whenever adding the current character would exceed 100 pixels. The currentWidth
is reset to the current character's width in such a case. The numberOfLines
function returns a vector containing the total number of lines and the width of the last line.
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.
1def numberOfLines(widths, s):
2 total_lines = 1
3 prefix_sum = [0] * (len(s) + 1)
4
5 for i in range(len(s)):
6 prefix_sum[i + 1] = prefix_sum[i] + widths[ord(s[i]) - ord('a')]
7
8 last_valid = 0
9
10 for i in range(1, len(s) + 1):
11 if prefix_sum[i] - prefix_sum[last_valid] > 100:
12 total_lines += 1
13 last_valid = i - 1
14
15 last_width = prefix_sum[len(s)] - prefix_sum[last_valid]
16 return [total_lines, last_width]
17
18# Example Usage
19widths = [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]
20s = "bbbcccdddaaa"
21print(numberOfLines(widths, s))
22
In Python, the prefix sum list is built and used to check when new lines should begin. The technique identifies when accumulated width measurements overstep the 100-pixel limit, thus dictating consecutive line increments for line counting accordingly.