806. Number of Lines To Write String
https://leetcode.com/problems/number-of-lines-to-write-string/
js
/**
* @param {number[]} widths
* @param {string} S
* @return {number[]}
*/
var numberOfLines = function(widths, S) {
const widthMap = 'abcdefghijklmnopqrstuvwxyz'.split('').reduce((ret, l, i) => {
ret[l] = widths[i]
return ret
}, {})
let lines = 0
let units = 0
S.split('').forEach(l => {
if (units + widthMap[l] > 100) {
lines += 1
units = widthMap[l]
} else {
units += widthMap[l]
}
})
return [lines + 1, units]
}
py
class Solution:
def numberOfLines(self, widths, S):
"""
:type widths: List[int]
:type S: str
:rtype: List[int]
"""
lines = 0
units = 0
for l in S:
width = widths[ord(l) - 97]
if units + width > 100:
lines += 1
units = width
else:
units += width
return [lines + 1, units]