You are given a string s of lowercase English letters and an array widths
denoting how many pixels wide each lowercase English letter is.
Specifically, widths[0] is the width of 'a', widths[1] is the width of
'b', and so on.
You are trying to write s across several lines, where each line is no longer than100pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100
pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.
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: You can write s as follows:abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is60 pixels wide.
Input: 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], s ="bbbcccdddaaa"Output: [2,4]Explanation: You can write s as follows:bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is4 pixels wide.
We want to fit as many letters as possible on each line without exceeding 100 pixels. For each character, add its width to the current line; if it exceeds 100, start a new line.
#include<vector>#include<string>usingnamespace std;
classSolution {
public: vector<int> numberOfLines(vector<int>& widths, string s) {
int lines =1, cur =0;
for (char c : s) {
int w = widths[c-'a'];
if (cur + w >100) { ++lines; cur = w; }
else cur += w;
}
return {lines, cur};
}
};
classSolution {
publicint[]numberOfLines(int[] widths, String s) {
int lines = 1, cur = 0;
for (char c : s.toCharArray()) {
int w = widths[c-'a'];
if (cur + w > 100) { lines++; cur = w; }
else cur += w;
}
returnnewint[]{lines, cur};
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funnumberOfLines(widths: IntArray, s: String): IntArray {
var lines = 1; var cur = 0for (c in s) {
val w = widths[c-'a']
if (cur + w > 100) { lines++; cur = w }
else cur += w
}
return intArrayOf(lines, cur)
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defnumberOfLines(self, widths: list[int], s: str) -> list[int]:
lines, cur =1, 0for c in s:
w = widths[ord(c)-ord('a')]
if cur + w >100:
lines +=1; cur = w
else:
cur += w
return [lines, cur]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnnumber_of_lines(widths: Vec<i32>, s: String) -> Vec<i32> {
letmut lines =1;
letmut cur =0;
for c in s.chars() {
let w = widths[(c asu8-b'a') asusize];
if cur + w >100 {
lines +=1; cur = w;
} else {
cur += w;
}
}
vec![lines, cur]
}
}