leetcode 68. Text Justification

136 篇文章 0 订阅

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ’ ’ when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.

给定一个单词数组,和每行的字符数,按照要求匹配
首先判断下每行:
当前tmp中存储的单词的长度flag+该单词长度<=maxWidth
如果满足,则将该单词加入到tmp中
如果不满足,tmp数组直接进行规范化(modify()函数)
注意到最后一段是按照正常的输出格式,少的部分进行空格补全

class Solution(object):
    def modify(self,tmpwords,maxWidth):
        """
        :type tmpwords:List[str] eg:['This','is','an']
        :type maxWidth: int 
        """
        word_count=len(tmpwords)
        space_count=max(1,word_count-1)
        character_num=sum([len(i) for i in tmpwords])
        base_space=(maxWidth-character_num)/space_count
        extra_space=(maxWidth-character_num)%space_count
        ret=''
        for i in range(space_count):
            ret=ret+tmpwords[i]+''.join([' ']*base_space)
            if i<extra_space:
                ret=ret+' '
        if word_count>1:
            ret=ret+tmpwords[-1]
        return ret
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        result=[]
        tmp=[]
        flag=0
        for i in words:
            if flag+len(i)<=maxWidth:
                tmp.append(i)
                flag=flag+len(i)+1
            else:
                if len(tmp):
                    result.append(self.modify(tmp,maxWidth))
                tmp=[i]
                flag=len(i)+1
        ans=''
        for i in tmp[0:len(tmp)-1]:
            ans=ans+i+' '
        if len(tmp):
            ans=ans+tmp[-1]
        ans=ans+''.join([' ']*(maxWidth-len(ans)))
        result.append(ans)
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值