【leetcode刷题】68 Text Justification (python)

原题链接
https://leetcode.com/problems/text-justification/
解题思路
首先分为末行和非末行
对于非末行:
空格数至少为字符数-1。用count_char记录字符数,当字符数超过maxWidth-num_space时,所有指数往回回溯一轮。
然后开始将几个词写入当前行。需要计算一下需要多空格的词的个数,然后写入即可。
对于末行:
每写入一个字,直接空1格,字都写进去以后,补空格补足maxWidth即可。
在这里插入图片描述

代码

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        i = 0
        count_char = 0
        count_word = 0
        string = ''
        ans = []
        while i<len(words):
            # 在没超出量程之前一直加word
            count_char += len(words[i])
            count_word += 1
            if count_char<=maxWidth - (count_word-1):
                i += 1
                continue
            # 超出量程,所以数目先回退一位
            count_char -= len(words[i])
            count_word -= 1
            if count_word == 1:
                num_space = count_word
            else:
                num_space = count_word - 1
            i -= 1
            # 计算两两单词之间空格的数目,并且用space_width_plus表示前几位空格有余
            space_width = (maxWidth - count_char) // num_space
            space_width_plus = (maxWidth - count_char) % num_space

            for index in range(count_word - 1, -1, -1):
                string += words[i - index]
                if index==0 and count_word!=1:
                    break
                if index>num_space-space_width_plus:
                    string += ' ' * (space_width + 1)
                else:
                    string += ' ' * space_width
            ans.append(string[:])
            count_char = 0
            count_word = 0
            string = ''
            i += 1
        i -= count_word
        for index in range(i, len(words)-1):
            string += words[index] + ' '
        string += words[len(words)-1]
        while len(string) < maxWidth:
            string += ' '
        ans.append(string)
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值