This is the Text Justification challenge at LeetCode:
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. "]
Clarifications:
For any two words, there is at least one space between them. This is also true for the last line.
A line other than the last line might contain only one word. In this case, the line should be left-justified.
class Solution:
# @param {string[]} words
# @param {integer} maxWidth
# @return {string[]}
def fullJustify(self, words, maxWidth):
num_of_words = len(words)
start_ind, end_ind, runner = 0, 0, 0
len_of_line, word_num_line = 0, 0
res = []
while True:
runner = start_ind
if runner >= num_of_words:
break
len_of_line, word_num_line = 0, 0
#find the start and end word indexes for one line
while runner < num_of_words:
len_of_line = len_of_line + len(words[runner])
word_num_line = word_num_line + 1
if runner != start_ind:
len_of_line = len_of_line + 1
if len_of_line > maxWidth:
break
runner = runner + 1
#justify one line
if runner != num_of_words:
end_ind = runner - 1
if start_ind == end_ind: #one word in a line
oneline = words[start_ind] + " "*(maxWidth-len(words[start_ind]))
else: #many words in a line
len_of_line = len_of_line - len(words[runner]) - 1
word_num = end_ind - start_ind + 1
extra_spaces = maxWidth - (len_of_line - (word_num - 1))
basic_pad_spaces = extra_spaces // (word_num - 1)
addition_pad_spaces = extra_spaces % (word_num - 1)
oneline = ""
for ind in range(start_ind, runner-1):
oneline = oneline + words[ind] + " "*basic_pad_spaces
if ind - start_ind < addition_pad_spaces:
oneline = oneline + " "
oneline = oneline + words[runner-1]
else: #last line
oneline = ""
for ind in range(start_ind, num_of_words-1):
oneline = oneline + words[ind] + " "
oneline = oneline + words[num_of_words-1]
pad_spaces = maxWidth - len(oneline)
oneline = oneline + " "*pad_spaces
res.append(oneline)
start_ind = runner
return res