您当前的位置: 首页 >  leetcode

孑渡

暂无认证

  • 1浏览

    0关注

    178博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Leetcode】每日一题:写字符串需要的行数

孑渡 发布时间:2022-04-12 10:27:30 ,浏览量:1

写字符串需要的行数

我们要把给定的字符串 S 从左到右写到每一行上,每一行的最大宽度为100个单位,如果我们在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行。我们给定了一个数组 widths ,这个数组 widths[0] 代表 ‘a’ 需要的单位, widths[1] 代表 ‘b’ 需要的单位,…, widths[25] 代表 ‘z’ 需要的单位。 现在回答两个问题:至少多少行能放下S,以及最后一行使用的宽度是多少个单位?将你的答案作为长度为2的整数列表返回。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/number-of-lines-to-write-string

AC代码
class Solution:
    def numberOfLines(self, widths: List[int], s: str) -> List[int]:
        num_line = 1
        current_vol = 100
        for letter in s:
            if current_vol >= widths[ord(letter) - ord('a')]:
                current_vol -= widths[ord(letter) - ord('a')]
            else:
                num_line += 1
                current_vol = 100 - widths[ord(letter) - ord('a')]
        return [num_line, 100 - current_vol]
官方代码
class Solution:
    def numberOfLines(self, widths: List[int], s: str) -> List[int]:
        MAX_WIDTH = 100
        lines, width = 1, 0
        for c in s:
            need = widths[ord(c) - ord('a')]
            width += need
            if width > MAX_WIDTH:
                lines += 1
                width = need
        return [lines, width]


# 作者:LeetCode-Solution

简单题,懂得都懂,也掀不起什么波浪

关注
打赏
1663211900
查看更多评论
立即登录/注册

微信扫码登录

0.0387s