Leetcode 806. Number of Lines To Write String
You are given a list widths
, where widths[0]
is the width of ‘a’, widths[1]
is the width of ‘b’, …, and widths[25]
is the width of ‘z’. Given a string s
, write it onto several lines such that each line has a maximum width of 100 units. You should pack your words in a greedy manner; that is, you want to pack as many words as possible in each line. Return an array result
of length 2 where:
result[0]
is the total number of lines.result[1]
is the width of the last line in units.Input:
widths = [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,10]
s = "abcdefghijklmnopqrstuvwxyz"
Output: [3, 60]
Explanation:
All letters have the same length of 10. To write all 26 letters,
we need two full lines (each with 100 units) and one line with 60 units.
s
consists only of lowercase English letters.s
will contain only characters from ‘a’ to ‘z’.[0, 0]
.lines
to 1 because there’s at least one line if the string is not empty.current_width
to 0 to keep track of the current line width.s
:
widths
array.lines
count.current_width
to the width of the current character.current_width
.lines
and current_width
(width of the last line).The time complexity of this solution is O(n), where n
is the length of the input string s
. We iterate through the string once, and all other operations (such as accessing the widths
array) are O(1).
public class Solution {
public int[] numberOfLines(int[] widths, String s) {
int lines = 1;
int currentWidth = 0;
for (char c : s.toCharArray()) {
int width = widths[c - 'a'];
if (currentWidth + width > 100) {
lines++;
currentWidth = width;
} else {
currentWidth += width;
}
}
return new int[]{lines, currentWidth};
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?