68 Text Justification

Given an array of words and a lengthL, format the text such that each line has exactlyLcharacters 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 exactlyLcharacters.

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 exceedLin length.

Nearly working:

  • It seems to me that many of the rules are too arbitrary, with many edge cases.

import math


def normalize_text(current_words, max_width):
    """
    :type current_words: List[str]
    :type max_width: int
    :rtype: string
    """
    if (len(current_words) == 1):
        return current_words[0] + " " * (abs(max_width - len(current_words[0])))

    # accumulate the total length of the array
    cumulative_len = 0
    for word in current_words:
        cumulative_len += len(word)

    left_over_spaces = abs(max_width - cumulative_len)

    # divide the spaces evenly between the words
    # -1 in order to not account for the last word
    spaces_per_word = left_over_spaces / (len(current_words) - 1)
    discrete_spaces_per_word = int(spaces_per_word)

    iter = 0
    # add set amount of spaces, dicluding the last word
    while (iter < len(current_words) - 1):
        current_words[iter] += (" " * discrete_spaces_per_word)
        iter += 1

    # add the remaining bits spread equally through all the words
    remaining_spaces = left_over_spaces - (discrete_spaces_per_word * (len(current_words) - 1))
    word_iter = 0
    while (remaining_spaces > 0):
        wrapper = word_iter % len(current_words)
        current_words[wrapper] +=  " "
        word_iter += 1
        remaining_spaces -= 1

    # now append to single string
    cum_str = ""
    for word in current_words:
        cum_str += word

    return cum_str


def fullJustify(words, maxWidth):
    """
    :type words: List[str]
    :type maxWidth: int
    :rtype: List[str]['']
    """
    if (len(words) == 0 or words[0] == ''):
        return [' ' * maxWidth];

    justified_text = []
    row_string = []
    cur_width = 0
    iter = 0

    while (iter < len(words)):
        # +1 to account for additional space after word
        # except for the last word
        if (iter + 1 < len(words) and cur_width + len(words[iter]) + 1 < maxWidth):
            cur_width += len(words[iter]) + 1
        else:
            cur_width += len(words[iter])

        if (cur_width > maxWidth):
            justified_text.append(normalize_text(row_string, maxWidth))

            # consider previously ignored word
            iter -= 1
            row_string = []
            cur_width = 0

        else:
            row_string.append(words[iter])

        iter += 1

    # edge case: next iteration may contain data
    if (len(row_string) > 0):
        justified_text.append(normalize_text(row_string, maxWidth))
    return justified_text


print(fullJustify(["What","must","be","shall","be."], 12))
print(fullJustify(["a","b","c","d","e"], 1))
print(fullJustify(["a"], 1))
print(fullJustify([""], 0))
print(fullJustify([""], 2))
print(fullJustify(["This", "is", "an", "example", "of", "text", "justification."], 16))

Last updated