LeetCode Text Justification

LeetCode解题之Text Justification


原题

把一个集合的单词按照每行L个字符存放,不足的在单词间添加空格,每行要两端对齐(即两端都要是单词),如果空格不能均匀分布在所有间隔中,那么左边的空格要多于右边的空格,最后一行靠左对齐,每个单词间一个空格。

注意点:

  • 单词的顺序不能发生改变
  • 中间行也可能出现只有一个单词,这时要靠左对齐
  • 每行要尽可能多的容纳单词

例子:

输入: words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”], maxWidth = 16

输出:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

解题思路

这道题比较繁琐,题目就一大段。采用双指针的方法来标记当前行的单词,如果加上下一个单词的长度和每个单词间至少一个空格时的总长度大于目标长度,说明此时的单词就是该行应该存放的。要分是否只有一个单词还是多个单词进行讨论,如果有多个单词,需要平均分配单词间的空格。现在可以知道总的空格数和单词间隔数,所以计算单词间的间隔比较简单,注意多余的空格要优先添加到左边的单词间隔中。不要忘记添加最后一行的单词。

AC源码

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        start = end = 0
        result, curr_words_length = [], 0
        for i, word in enumerate(words):
            if len(word) + curr_words_length + end - start  > maxWidth:
                if end - start == 1:
                    result.append(words[start] + ' ' * (maxWidth - curr_words_length))
                else:
                    total_space = maxWidth - curr_words_length
                    space, extra = divmod(total_space, end - start - 1)
                    for j in range(extra):
                        words[start + j] += ' '
                    result.append((' ' * space).join(words[start:end]))
                curr_words_length = 0
                start = end = i
            end += 1
            curr_words_length += len(word)
        result.append(' '.join(words[start:end]) + ' ' * (maxWidth - curr_words_length - (end - start - 1)))
        return result


if __name__ == "__main__":
    assert Solution().fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16) == [
        "This    is    an",
        "example  of text",
        "justification.  "
    ]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值