LeetCode Text Justification

来源:互联网 发布:java 图片相似度对比 编辑:程序博客网 时间:2024/06/05 14:37

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 resultif __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 0