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.
public class Solution {
public static int[] NumberOfLines(int[] widths, string s) {
int totalLines = 1;
int currentWidth = 0;
foreach (char c in s) {
int charWidth = widths[c - 'a'];
if (currentWidth + charWidth > 100) {
totalLines++;
currentWidth = charWidth;
} else {
currentWidth += charWidth;
}
}
return new int[] { totalLines, currentWidth };
}
public static void Main(string[] args) {
int[] widths = new int[]{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";
int[] result = NumberOfLines(widths, s);
Console.WriteLine($"[{result[0]}, {result[1]}]");
}
}
In the C# solution, NumberOfLines
method processes each character's width by mapping it to the corresponding index in the widths array, updating totalLines
and currentWidth
using a similar approach as in other languages.
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.
1import java.util.ArrayList;
2import java.util.List;
3
4public class Solution {
5 public static int[] numberOfLines(int[] widths, String s) {
6 int totalLines = 1;
7 int[] prefixSum = new int[s.length() + 1];
8 prefixSum[0] = 0;
9
10 for (int i = 0; i < s.length(); ++i) {
11 prefixSum[i + 1] = prefixSum[i] + widths[s.charAt(i) - 'a'];
12 }
13
14 int lastValid = 0;
15 for (int i = 1; i <= s.length(); ++i) {
16 if (prefixSum[i] - prefixSum[lastValid] > 100) {
17 totalLines++;
18 lastValid = i - 1;
19 }
20 }
21 return new int[]{totalLines, prefixSum[s.length()] - prefixSum[lastValid]};
22 }
23
24 public static void main(String[] args) {
25 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};
26 String s = "bbbcccdddaaa";
27 int[] result = numberOfLines(widths, s);
28 System.out.printf("[%d, %d]\n", result[0], result[1]);
29 }
30}
31
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.