码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】68. Text Justification

时间:2018-08-20 19:43:33      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:pop   last   color   text   分享图片   strong   app   form   要求   

题目如下:

技术分享图片

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

代码如下:

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
        

 

【leetcode】68. Text Justification

标签:pop   last   color   text   分享图片   strong   app   form   要求   

原文地址:https://www.cnblogs.com/seyjs/p/9499722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!