给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。
你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ’ ’ 填充,使得每行恰好有 maxWidth 个字符。
要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。
文本的最后一行应为左对齐,且单词之间不插入额外的空格。
说明:
单词是指由非空格字符组成的字符序列。
每个单词的长度大于 0,小于等于 maxWidth。
输入单词数组 words 至少包含一个单词。
示例:
输入:
words = [“This”, “is”, “an”, “example”, “of”, “text”, “justification.”]
maxWidth = 16
输出:
[
“This is an”,
“example of text”,
"justification. "
]
示例 2:
输入:
words = [“What”,“must”,“be”,“acknowledgment”,“shall”,“be”]
maxWidth = 16
输出:
[
“What must be”,
"acknowledgment ",
"shall be "
]
解释: 注意最后一行的格式应为 "shall be " 而不是 “shall be”,
因为最后一行应为左对齐,而不是左右两端对齐。
第二行同样为左对齐,这是因为这行只包含一个单词。
示例 3:
输入:
words = [“Science”,“is”,“what”,“we”,“understand”,“well”,“enough”,“to”,“explain”,
“to”,“a”,“computer.”,“Art”,“is”,“everything”,“else”,“we”,“do”]
maxWidth = 20
输出:
[
“Science is what we”,
“understand well”,
“enough to explain to”,
“a computer. Art is”,
“everything else we”,
"do "
]
逻辑理顺就好了:
class Solution:
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
left, right, count, len_w = 0, 0, 0, len(words) # 左右指针位置和放置长度
res = []
while left < len_w:
right, count, one_row = left, len(words[left]), ''
while right+1 < len_w and (count+1+len(words[right+1])) <= maxWidth:
count += 1+len(words[right+1])
right += 1
if right < len_w-1: # 非最后一行
if right-left > 0: # 多个单词
a = (maxWidth-count) // (right-left) # 单词之间至少填充空格数
b = (maxWidth-count) % (right-left) # 前b个单词要多填充一个空格
for i in range(left, right):
one_row += words[i] + " " * (a+1)
if i-left < b:
one_row += ' '
one_row += words[right]
else: # 一个单词
one_row = words[left]
while len(one_row) < maxWidth:
one_row += ' '
res.append(one_row)
left = right+1
else: # 最后一行
for i in range(left, len_w-1):
one_row += words[i] + ' '
one_row += words[-1]
while len(one_row) < maxWidth:
one_row += ' '
res.append(one_row)
break
return res