leetcode68. Text Justification

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode68. Text Justification相关的知识,希望对你有一定的参考价值。

题目如下:

解题思路:解题方法没啥好说的,按题目要求来,最后一行左对齐,以及空格数不能被均分的时候,从左往右优先分配。

代码如下:

class Solution(object):
    def format(self,line,length,maxWidth,res):
        diff = maxWidth - length
        remainder = 0
        if (len(line) - 1) > 1:
            interval = diff / (len(line) - 1)
            remainder = diff % (len(line) - 1)
        else:
            interval = diff
        w = \'\'
        for inx, val in enumerate(line):
            w += val
            if inx != len(line) - 1 or len(line) == 1:
                if remainder > 0:
                    w += \' \' * (interval + 1)
                    remainder -= 1
                else:
                    w += \' \' * (interval)
        res.append(w)

    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        line = []
        length = 0
        res = []
        for i,v in enumerate(words):
            if len(line) - 1 + length + len(v) >= maxWidth:
                self.format(line,length,maxWidth,res)
                line = []
                length = 0
            length += len(v)
            line.append(v)
        if len(line) > 0:
            self.format(line, length, maxWidth, res)

        last = res.pop(-1)
        last_char = None
        formats = \'\'
        for i in last:
            if last_char == \' \' and i == \' \':
                continue
            formats += i
            last_char = i
        formats += \' \' * (maxWidth - len(formats))
        res.append(formats)
        return res
        

 

以上是关于leetcode68. Text Justification的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 68 Text Justification ----- java

[leetcode]68. Text Justification文字对齐

LeetCode -- 68.Text Justification

LeetCode 68: Text Justification

一天一道LeetCode#68. Text Justification

LeetCode 68. Text Justification