python - text justify

• ``````class Solution(object):

def left_justify(self, row, width):
s = " ".join(row)
s += " " * (width - len(s))
return s

def row_to_str(self, row, width):
s = ""
n_slot = len(row) - 1
if not n_slot:
return self.left_justify(row, width)

n_char = sum([len(word) for word in row])
n_space_per_slot = (width - n_char) / n_slot
n_extra_space = (width - n_char) % n_slot

s += row[0]
for word in row[1:]:
s += " " * n_space_per_slot
if n_extra_space:
s += " "
n_extra_space -= 1
s += word

return s

def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
if not words:
return []

ans = []
curr_row = []
curr_len = len(curr_row)
for w in words:
if curr_len + len(w) > maxWidth:
res = self.row_to_str(curr_row, maxWidth)
ans.append(res)
curr_row = []
curr_len = len(curr_row)

curr_row.append(w)
curr_len += len(w)

if curr_len + 1 > maxWidth:
res = self.row_to_str(curr_row, maxWidth)
ans.append(res)
curr_row = []
curr_len = len(curr_row)
else:
curr_len += 1

# process last row
if len(curr_row):
s = self.left_justify(curr_row, maxWidth)
ans.append(s)

return ans
``````

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