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
                
    
  • 相关阅读:
    系统实践2-2:查看dockerfile-032092135mysql容器的配置信息
    系统综合实践1
    SDN——实验脚本7-2:hardtimeout.json
    SDN——实验脚本7-1:odlnorth.py
    实验 7:OpenDaylight 实验——Python 中的 REST API 调用
    预习非数值数据的编码方式
    预习原码补码
    C语言ll作业01
    C语言寒假大作战04
    C语言寒假大作战03
  • 原文地址:https://www.cnblogs.com/absolute/p/5678055.html
Copyright © 2011-2022 走看看