Text Justification

  • Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

  • You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ’ ’ when necessary so that each line has exactly L characters.

  • Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

  • For example,
    words: [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
    L: 16.

  • Return the formatted lines as:
    [
    “This is an”,
    “example of text”,
    “justification. ”
    ]

Note: Each word is guaranteed not to exceed L in length.
这一题需要注意的细节很多,考虑的不全面都不会被accept的。
class Solution:
    # @param words, a list of strings
    # @param L, an integer
    # @return a list of strings
    def fullJustify(self, words, L):
        output = []
        result = []
        length = 0
        last = False


        for i in range(len(words) - 1):
            length += len(words[i])
            if (length + len(output)) <= L:
                output.append(words[i])

            temp = ""
            if (length + len(output) + len(words[i+1])) > L:
                if (len(output) - 1) == 0:
                    div = L-length
                    temp += output[0] + div *' '
                else:
                    div = (L - length) / (len(output) - 1)
                    mod = (L - length) % (len(output) - 1)
                    for j in range(len(output) - 1):
                        temp += output[j] + div *' '
                        if (j +1) <= mod:
                            temp += ' '

                    temp += output[-1]
                result.append(temp)
                output = []
                length = 0

            if (length + len(output) + len(words[i+1])) < L and i == (len(words) -2):
                output.append(words[i+1])
                length += len(words[i+1])
                temp = ""
                last = True
                div = (L - length - len(output) + 1)
                for j in range(len(output) - 1):
                    temp += output[j] + ' '
                temp += output[-1] + div * ' '
                result.append(temp)



        if not last:
            result.append(words[-1] + (L - len(words[-1])) * ' ')
        return result

你可能感兴趣的:(Text Justification)