Text Justification
Problem: Text Justification
The difficulties lies in the fact that there are too many details. We can first store words in a same level together and when we scan a word belongs to the next level, we can add stored to our results and start storing a new row.
Code in Python:
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
res = []
def addWord(level, totalLen):
if len(level) == 1: res.append(level[0] + " " * (maxWidth-len(level[0])))
else:
string = ""
space, left = divmod((maxWidth - totalLen), (len(level)-1))
for word in level:
if left:
string += word + " " * (space + 1)
left -= 1
else: string += word + " " * space
res.append(string[:maxWidth])
level, length, _length = [], 0, 0
for word in words:
if length + len(word) <= maxWidth:
level.append(word)
length += len(word) + 1
_length += len(word)
else:
addWord(level, _length)
level, length, _length = [word], len(word)+1, len(word)
if level:
string = ""
for word in level:
string += word + " "
string += " " * (maxWidth-len(string))
res.append(string[:maxWidth])
return res