Clean python solution


  • 0
    I
    class Solution(object):
        def fullJustify(self, words, maxWidth):
            """
            :type words: List[str]
            :type maxWidth: int
            :rtype: List[str]
            """
            if not words:
                return []
                
            justifiedLines = []
            firstWordIdx = 0
            lineLen = len(words[0])
            for i in xrange(1, len(words)):
                if lineLen + 1 + len(words[i]) <= maxWidth:
                    lineLen += (1 + len(words[i]))
                else:
                    line = self.generateEvenSpacedLine(firstWordIdx, i - 1, maxWidth, words, lineLen)
                    justifiedLines.append(line)
                    firstWordIdx = i
                    lineLen = len(words[i])
                    
            lastLine = self.generateLeftJustifiedLine(firstWordIdx, len(words) - 1, maxWidth, words, lineLen)
            justifiedLines.append(lastLine)
            return justifiedLines
            
        def generateEvenSpacedLine(self, firstWordIdx, lastWordIdx, maxWidth, words, lineLen):
            numWords = lastWordIdx - firstWordIdx + 1
            if numWords == 1:
                return words[firstWordIdx] + ' '*(maxWidth - lineLen)
             
            numGaps = numWords - 1   
            spaceToDistr = maxWidth - lineLen
            gapSpace, extraGaps = divmod(spaceToDistr, numGaps)
            line = words[firstWordIdx]
            
            for i in xrange(firstWordIdx + 1, lastWordIdx + 1):
                line += (' '*(gapSpace + 1))
                if extraGaps > 0:
                    line += ' '
                    extraGaps -= 1
                
                line += words[i]
                    
            return line
            
        def generateLeftJustifiedLine(self, firstWordIdx, lastWordIdx, maxWidth, words, lineLen):
            line = words[firstWordIdx]
            for i in xrange(firstWordIdx + 1, lastWordIdx + 1):
                line += (' ' + words[i])
            line += (' '*(maxWidth - len(line)))
            return line
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.