【leetcode】806. Number of Lines To Write String

84.36%

note:   string.ascii_letters     string.digits

import string
class Solution(object):
    def numberOfLines(self, widths, S):
        """
        :type widths: List[int]
        :type S: str
        :rtype: List[int]
        """
        line = 0
        len_dict = {}
        for i in range(26):
            len_dict[string.ascii_letters[i]] = widths[i]
        sums = 0
        for char in S:
            sums += len_dict[char]
            if sums>100:
                line += 1
                sums = len_dict[char]
        return[line+1,sums]

----------------------------------

print chr(48), chr(49), chr(97)     #0,1,'a'

print ord('0'),ord('1'),ord('a')       #48,49,97

95.93%

class Solution(object):
    def numberOfLines(self, widths, S):
        """
        :type widths: List[int]
        :type S: str
        :rtype: List[int]
        """
        line = 1
        sums = 0
        for char in S:
            w = widths[ord(char)-ord('a')]
            sums += w
            if sums>100:
                line += 1
                sums = w
        return[line,sums]

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/80757920