Text Justification Python


  • 0
    def fullJustify(words, maxWidth):
        L = maxWidth
        curr_line = ''
        curr_length = 0
        strings = []
        curr_words = []
        ind = 0
        while(ind < len(words)):
            w = words[ind]
            if len(w) > L:
                return ''
            if curr_length + len(w) == L:
                curr_line = curr_line + w
                strings.append(curr_line)
                curr_length = 0
                curr_line = ''
                curr_words = []
                ind += 1
                continue
            if curr_length + len(w) < L:
                curr_line = curr_line + w + ' '
                curr_length = curr_length + len(w) + 1
                curr_words.append(w)
                if ind == len(words) - 1:
                    curr_line = curr_line + ' ' * (L - curr_length)
                    strings.append(curr_line)
                    break
                ind += 1
            else:
                spaces = L - curr_length
                total_spaces = len(curr_words) + spaces
                ct = len(curr_words)-1
                if ct == 0:
                    ct = 1
                space_per_word = total_spaces / ct
                rem_spaces = total_spaces % ct
                if len(curr_words) == 1:
                    curr_line = curr_words[0] + ' ' * space_per_word
                else:
                    space_index = [space_per_word for _ in range(ct)]
                    i = 0
                    curr_line = ''
                    while rem_spaces > 0:
                        space_index[i] += 1
                        i += 1
                        rem_spaces -= 1
                    temp_words = curr_words[:-1]
                    for i, word in enumerate(temp_words):
                        curr_line = curr_line + word + ' ' * space_index[i]
                    curr_line = curr_line + curr_words[-1]
                strings.append(curr_line)
                curr_length = 0
                curr_line = ''
                curr_words = []
                if len(w) > L:
                    return ''
        return strings
    

Log in to reply
 

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