6.27 - hard - 16

68. Text Justification

这题其实也怪怪的,这种题目怎么能算在难题行列呢?解题的想法就是先把每一个row的词找出来,然后再分配空格,最后一行要特殊处理

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        index = 0
        cur_length = 0
        row = []
        res = []
        while index < len(words):
            if len(words[index]) + cur_length <= maxWidth:
                row.append(words[index])
                cur_length += len(words[index]) + 1
                index += 1
            else:
                # process row
                self.process(row, maxWidth, res)
                # reset row
                row = []
                cur_length = 0
        if row:
            cur_length = 0
            l = ""
            for word in row:
                l += word + " "
            if len(l) <= maxWidth:
                res.append(l+(maxWidth-len(l))*" ")
            else:
                res.append(l[:-1])
        return res

    def process(self, row, maxWidth, res):
        spaces = maxWidth - len("".join(row))
        if len(row) == 1:
            res.append(row[0]+spaces*" ")
        else:
            space_list = [0 for _ in range(len(row)-1)]
            i = 0
            while spaces:
                space_list[i] += 1
                spaces -= 1
                i += 1
                i %= len(space_list)
            
            line = ""
            for i in range(len(row)-1):
                line += row[i] + space_list[i]*" "
            res.append(line+row[-1])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,042评论 18 399
  • 花开无声,花谢有声。 和人的一生正好相反, 人出生时总会伴着哇哇大哭的声音, 但人在离开时,往往会悄然无声。
    喜儿的小日子阅读 3,097评论 0 5
  • 这张照片,传遍了今天文山州的朋友圈。无论男女老少,从事各种职业,都有人转发。 这张照片,有一位老母亲和她的...
    宁歌911阅读 1,573评论 0 0
  • 那个春天的夜晚,樱花园的香气弥漫了整个校园,月光也显得格外皎洁。那个男孩鼓起十足的勇气,抱着那封不知道被自己改过多...
    989bfd732fe3阅读 1,573评论 0 3