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.
In Java, we employ the same greedy approach using an int[]
to hold the results. Like the previous examples, we increase totalLines
when needed and adjust currentWidth
accordingly, iterating through the string using a for-each loop over its character array representation.
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#include <iostream>
2#include <vector>
3using namespace std;
4
5vector<int> numberOfLines(vector<int>& widths, string s) {
6 int totalLines = 1;
7 vector<int> prefixSum(s.size() + 1);
8 prefixSum[0] = 0;
9
10 for (int i = 0; i < s.size(); ++i) {
11 prefixSum[i + 1] = prefixSum[i] + widths[s[i] - 'a'];
12 }
13
14 int lastWidth = 0;
15 for (int i = 1; i <= s.size(); ++i) {
16 if (prefixSum[i] - prefixSum[lastWidth] > 100) {
17 totalLines++;
18 lastWidth = i - 1;
19 }
20 }
21
22 return {totalLines, prefixSum[s.size()] - prefixSum[lastWidth]};
23}
24
25int main() {
26 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};
27 string s = "bbbcccdddaaa";
28 vector<int> result = numberOfLines(widths, s);
29 cout << "[" << result[0] << ", " << result[1] << "]" << endl;
30 return 0;
31}
32
The prefix sum array in C++ tracks cumulative widths, and we iteratively check where the designated line limits are exceeded, dictating new start points for lines and counting their totals. This implements an efficient loop based on cumulative line length calculations.