Leetcode 806. Number of Lines To Write String
You are given a string s of lowercase English letters and an array widths, where widths[0] represents the width of the character 'a', widths[1] represents the width of the character 'b', and so on. Describe how many lines have been written and the width used in the last line given.
The paper has a set width of 100 units, and strings are written from left to right on the paper without any spaces. Each substring fits as many words as possible without exceeding the width 100 units.
You need to output an array resulted with two integers:
s.s will not be empty.widths always have exactly 26 elements?
widths array always has 26 elements.lines to 1 because at least one line will be required to start writing.current_width to 0 as nothing has been written yet.s:
widths array.current_width exceeds 100 units:
lines by 1 and reset current_width to the width of the current character.current_width.#include <vector>
#include <string>
std::vector<int> numberOfLines(std::vector<int>& widths, std::string s) {
int lines = 1;
int current_width = 0;
for (char c : s) {
int width = widths[c - 'a'];
if (current_width + width > 100) {
lines++;
current_width = width;
} else {
current_width += width;
}
}
return {lines, current_width};
}
n is the length of the string s:
widths array and performing constant-time arithmetic operations. Hence the time complexity is linear in relation to the length of the string s.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?