zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 26

    Text Justification

    细节实现题,基本结构是逐层填(外循环),maintain每层的start和end:start代表开始点,end在每层开始为start。在内层循环找到本层的end。找法是前向比较。最终end点落在本层end的下一个位置
    corner cases以及解法or错误点

    • 在内循环中end还要检查<n
    • 只有一个单词的行在一个分支处理,可能这个单词超过maxWidth or not,没超过要补空格
    • space和bonus:因为空格的长度是随着单词个数变动,用space和bonus来动态分配,公式见code
    • 最后一行要补空格,在python中因为每行用list表示string,所以还要记录行长
    class Solution(object):
        def fullJustify(self, words, maxWidth):
            """
            :type words: List[str]
            :type maxWidth: int
            :rtype: List[str]
            """
            if not words or maxWidth==0: return [""]
            start = 0
            end = 0
            n = len(words)
            res = []
            while start<n:
                l = 0
                end = start
                while end<n and l+len(words[end])+(end-start)<=maxWidth:
                    l+=len(words[end])
                    end+=1
                
                thisLevel = list()
                if end-start<=1: # 0 or 1 word
                    thisLevel.append(words[start])
                    if maxWidth-len(words[start])>0:
                        thisLevel.append(' '*(maxWidth-len(words[start])))
                    print thisLevel
                else:
                    lastLine = False
                    if end>=n: # last line
                        space = 1
                        bonus = 0
                        lastLine = True
                    else:
                        print end,start,l
                        space = (maxWidth-l)/(end-1-start)
                        bonus = (maxWidth-l)-space*(end-1-start)
                        print space, bonus
                    
                    thisLevel.append(words[start])
                    lenThisLevel = len(words[start])
                    for i in range(start+1, end):
                        thisLevel.append(' '*space)
                        lenThisLevel+=space
                        if bonus>0:
                            thisLevel.append(' ')
                            lenThisLevel+=1
                            bonus-=1
                        thisLevel.append(words[i])
                        lenThisLevel+=len(words[i])
                    
                    if lastLine:
                        print maxWidth, len(thisLevel)
                        thisLevel.append(' '*(maxWidth-lenThisLevel))
                res.append(''.join(thisLevel))
                start = end
            
            return res
                
    
  • 相关阅读:
    win10彻底永久关闭自动更新的方法
    kibana.yml配置
    完整记录安装elasticsearch的过程
    docker下nginx的安装
    centos7删除mysql
    21 | panic函数、recover函数以及defer语句 (上)
    07 | 数组和切片
    SNAPSHOT包上传nexus成功,下载失败
    extract method(提炼函数)
    枚举中不要再出现数字了
  • 原文地址:https://www.cnblogs.com/absolute/p/5678055.html
Copyright © 2011-2022 走看看