原题链接
https://leetcode.com/problems/text-justification/
解题思路
首先分为末行和非末行
对于非末行:
空格数至少为字符数-1。用count_char记录字符数,当字符数超过maxWidth-num_space时,所有指数往回回溯一轮。
然后开始将几个词写入当前行。需要计算一下需要多空格的词的个数,然后写入即可。
对于末行:
每写入一个字,直接空1格,字都写进去以后,补空格补足maxWidth即可。
代码
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
i = 0
count_char = 0
count_word = 0
string = ''
ans = []
while i<len(words):
# 在没超出量程之前一直加word
count_char += len(words[i])
count_word += 1
if count_char<=maxWidth - (count_word-1):
i += 1
continue
# 超出量程,所以数目先回退一位
count_char -= len(words[i])
count_word -= 1
if count_word == 1:
num_space = count_word
else:
num_space = count_word - 1
i -= 1
# 计算两两单词之间空格的数目,并且用space_width_plus表示前几位空格有余
space_width = (maxWidth - count_char) // num_space
space_width_plus = (maxWidth - count_char) % num_space
for index in range(count_word - 1, -1, -1):
string += words[i - index]
if index==0 and count_word!=1:
break
if index>num_space-space_width_plus:
string += ' ' * (space_width + 1)
else:
string += ' ' * space_width
ans.append(string[:])
count_char = 0
count_word = 0
string = ''
i += 1
i -= count_word
for index in range(i, len(words)-1):
string += words[index] + ' '
string += words[len(words)-1]
while len(string) < maxWidth:
string += ' '
ans.append(string)
return ans