Text Justification

两端对齐
首先算带一个空格最多一行可以放多少个单词,然后计算放单词以后的空格数目,这个数目需要进行均分,如果不平均,就左边尽可能均分
代码部分参考https://www.cnblogs.com/chruny/p/5045245.html

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        ans = []
        i = 0
        while i < len(words):
            size,begin = 0,i
            while i < len(words):
                if size == 0:
                    newsize = len(words[i])
                else:
                    newsize = size + len(words[i]) + 1
                if newsize <= maxWidth:
                    size = newsize
                else:
                    break
                i += 1
            s = maxWidth - size
            if i - begin - 1 > 0 and i < len(words):
                ns = s / (i - begin - 1)
                s %= i - begin - 1
            else:
                ns = 0
            j = begin
            while j < i:
                if j == begin: tmp = words[j]
                else:
                    tmp += ' '*(ns + 1)
                    if s > 0 and i < len(words):
                        tmp += ' '
                        s -= 1
                    tmp += words[j]
                j += 1
            tmp += ' '*s
            ans.append(tmp)
        return ans
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容