首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Leetcode-Easy 806. Number of Lines To Write String

Leetcode-Easy 806. Number of Lines To Write String

作者头像
致Great
发布2018-10-08 10:59:16
发布2018-10-08 10:59:16
5530
举报
文章被收录于专栏:自然语言处理自然语言处理

题目描述

给一个字符串S,从左到右将它们排列行,每行最大长度为100,,同时给定一个数组withds,widths[0]对应着 a的宽度, widths[1]对应着b的宽度, ..., widths[25] 对应着z的宽度。 求:至少需要多少行以及最后一行的长度 下面是一个实例:

代码语言:javascript
复制
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, 60]
Explanation: 
All letters have the same length of 10. To write all 26 letters,
we need two full lines and one line with 60 units.

260的宽度,需要排成2个100的行,第3行的长度为60,所以结果是[3,60]

思路

逐个排列S中的每个字母,每排一个字母,需要检查当前行长度是否大于100,大于100,行数加1,长度变成最后一个元素的宽度。

代码实现

代码语言:javascript
复制
class Solution:
    def numberOfLines(self, widths, S):
        """
        :type widths: List[int]
        :type S: str
        :rtype: List[int]
        """
        letter_list=list("abcdefghijklmnopqrstuvwxyz")
        
        length=0
        line=1
        
        for s in S:
            length+=widths[letter_list.index(s)]
            if length>100:
                line+=1
                length=widths[letter_list.index(s)]
                
        return [line,length]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.08.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 题目描述
  • 思路
  • 代码实现
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档