题目要求
We are to write the letters of a given string S
, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths
, an array where widths[0] is the width of ‘a’, widths[1] is the width of ‘b’, …, and widths[25] is the width of ‘z’.
Now answer two questions: how many lines have at least one character from S
, and what is the width used by the last such line? Return your answer as an integer list of length 2.
题目分析及思路
题目给出一个字符串和每个字母的长度数组,且限制每一行的最大值是100个单位,要求得到最后的行数和最后一行的宽度。可以遍历该字符串,每100个单位判断一下。
python代码
class Solution:
def numberOfLines(self, widths: ‘List[int]’, S: ‘str’) -> ‘List[int]’:
lines, width = 1, 0
for s in S:
w = widths[ord(s) – ord(‘a’)]
width += w
if width > 100:
lines += 1
width = w
return [lines, width]