思路:
先写小函数来确定一行中需要放几个单词(通过返回单词列表的开头和结尾),再确定空格的添加方法。
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
i = 0
n = len(words)
res = []
def one_row(i):
left = i
cur_row_len = len(words[i])
i += 1
while i < n:
if cur_row_len + len(words[i]) + 1 <= maxWidth:
cur_row_len += (len(words[i]) + 1)
i += 1
else:
break
return left, i
while i < n:
left, i = one_row(i)
one_row_words = words[left: i]
if i == n:
res.append(" ".join(one_row_words) + " " * (maxWidth - len(" ".join(one_row_words))))
break
num_space = maxWidth - len(