边工作边刷题: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
            
posted @ 2016-04-22 10:46  absolute100  阅读(108)  评论(0编辑  收藏  举报