68 Text Justification
[
"This is an",
"example of text",
"justification. "
]class Solution:
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
# maxWidth - num_of_letters is the amount of spaces that can fit
for i in range(maxWidth - num_of_letters):
# we need to fix the edge case when len(cur) == 1, and then we would mod by zero
cur[i%(len(cur)-1 or 1)] += ' '
res.append(''.join(cur))
cur, num_of_letters = [], 0
# once we reset, add the word that we overcounted
cur.append(w)
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]Last updated