Leetcode刷题:806. Number of Lines To Write String

这是leetcode contest 77的新题:
第一次参加contest,前边两道题确实简单。

version 1:

class Solution(object):
    def numberOfLines(self, widths, S):
        """
        :type widths: List[int]
        :type S: str
        :rtype: List[int]
        """
        letters = dict(zip('abcdefghijklmnopqrstuvwxyz',range(26)))
        lines = 1
        last_line = 0
        sum = 0
        for i in S:
            if sum + widths[letters[i]] <= 100:
                sum = sum + widths[letters[i]]
            else:
                lines += 1
                sum = widths[letters[i]]
            last_line = sum
        return [lines,last_line]

主要是dict和zip的用法,比较省事。

猜你喜欢

转载自blog.csdn.net/a529975125/article/details/79686619