Topic:
We are to write the letters of a given string S, from left to right into lines. Each line has maximum width units, and if writing a letter would cause the width of the "to exceed units, it I s 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 [] is the width of ' z '.
Now answer two questions:how many lines have in least one character from S, and what are the width used by the last such L Ine? Return your answer as an integer list of length 2.
Example:
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]
All
letters have the same length of 10. To write all letters, we are need two full lines and one line with
units.
Example:
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]
all
letters except ' a ' have the same length of nd
"Bbbcccdddaa" would cover 9 * ten + 2 * 4 = units.
For the last ' a ', it's written on the second line because there are only 2 units left in the the
.
So the answer are 2 lines, plus 4 units in the second line.
Analysis: the establishment of a letter for the key value, corresponding to the width of the dictionary; Traversal character to determine whether the added character will exceed a line width, if not exceeded, continue, otherwise put the next line
Code:
Class Solution (object):
def numberoflines (self, widths, S): ""
: Type Widths:list[int]
: Type S:str
: Rtype:list[int] ""
"
alphalst = Map (Chr,range (97,123))
alphawiddict = dict (Zip (alphalst,widths))
sumwidth = 0
linesnum = 1 for
x in S:
if Alphawiddict.get (x) < 100-sumwidth:
sumwidth + = Alph Awiddict.get (x)
else:
sumwidth = alphawiddict.get (x)
Linesnum + + 1 return
[Linesnum,sumwidth] If S else [0,0]
Thinking: