68. Text Justification
这题其实也怪怪的,这种题目怎么能算在难题行列呢?解题的想法就是先把每一个row的词找出来,然后再分配空格,最后一行要特殊处理
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
index = 0
cur_length = 0
row = []
res = []
while index < len(words):
if len(words[index]) + cur_length <= maxWidth:
row.append(words[index])
cur_length += len(words[index]) + 1
index += 1
else:
# process row
self.process(row, maxWidth, res)
# reset row
row = []
cur_length = 0
if row:
cur_length = 0
l = ""
for word in row:
l += word + " "
if len(l) <= maxWidth:
res.append(l+(maxWidth-len(l))*" ")
else:
res.append(l[:-1])
return res
def process(self, row, maxWidth, res):
spaces = maxWidth - len("".join(row))
if len(row) == 1:
res.append(row[0]+spaces*" ")
else:
space_list = [0 for _ in range(len(row)-1)]
i = 0
while spaces:
space_list[i] += 1
spaces -= 1
i += 1
i %= len(space_list)
line = ""
for i in range(len(row)-1):
line += row[i] + space_list[i]*" "
res.append(line+row[-1])