My python solution


  • 0
    def fullJustify(self, words, maxWidth):
        if not words:
            return []
        res = []
        left, right = 0, 1
        while right < len(words):
            temp_len = len(words[left])
            while right < len(words) and temp_len + len(words[right]) + 1 <= maxWidth:
                temp_len += len(words[right]) + 1
                right += 1
            if right == len(words):
                break
            size, dif = right - left, maxWidth - temp_len
            if size == 1:
                temp_str = words[left] + ' ' * dif
            else:
                spaces = [1 + dif / (size - 1) for i in xrange(size - 1)]
                dif -= (dif / (size - 1)) * (size - 1)
                for i in xrange(dif):
                    spaces[i] += 1
                temp_str = ""
                for i in xrange(size - 1):
                    temp_str += words[left + i] + ' ' * spaces[i]
                temp_str += words[left + size - 1]
            res.append(temp_str)
            left, right = right, right + 1
        temp_str = ""
        for i in xrange(left, right - 1):
            temp_str += words[i] + ' '
        temp_str += words[right - 1]
        res.append(temp_str + ' ' * (maxWidth - len(temp_str)))
        return res

Log in to reply
 

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