Catalog:
LC 68 Text Justification
[GoogleCall] LC 418 Sentence Screen Fitting
LC 68 Text Justification
words =["Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[ "Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "]
"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" was just a really long and awkward way to say round robin. The following line implements the round robin logic:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
Once you determine that there are only k words that can fit on a given line, you know what the total length of those words is num_of_letters. Then the rest are spaces, and there are (maxWidth - num_of_letters) of spaces. The "or 1" part is for dealing with the edge case len(cur) == 1.
So there are i spaces to allocation to k words, we keeping allocating from the left, when there are more paces than k, say 5 spaces and 4 words, spaces will be allocated at index 0, 1, 2, 3, 4 (actually should be 0,1,2,3) because we have k words and index should be 0-k-1, hence %(k-1)!
def fullJustify(self, words, maxWidth):
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
for i in range(maxWidth - num_of_letters):
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
cur += [w]
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
The method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(string).