题目描述
给定一个单词数组和一个长度 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 "
]
复制代码
解题思路: 贪心
- 使用贪心的思路, 尽可能的让一行放下更多的单词
- 当这一行放不下下一个单词时, 就重新开一行. 这样就可以得到每一行有哪些单词
- 根据每一行的单词, 填充空格
- 最后一行做单独处理
示例代码
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res, cur, l = [], [], 0
# 根据贪心, 计算每一行有哪些单词
for item in words:
if l + len(item) <= maxWidth:
l += (len(item) + 1)
cur.append(item)
else:
res.append(cur)
l = len(item) + 1
cur = [item]
res.append(cur)
# 根据每一行的单词进行空格填充
ans = []
for items in res[:-1]:
count = len(items)
if count == 1:
ans.append(items[0] + " " * (maxWidth - len(items[0])))
elif count == 2:
ans.append(items[0] + " " * (maxWidth - len(items[0]) - len(items[1])) + items[1])
else:
sumC = sum(len(i) for i in items)
m = (maxWidth - sumC) // (len(items) - 1)
n = (maxWidth-sumC) - m*(len(items) - 1)
a = items[0]
i = 1
for w in items[1:]:
if n > 0:
a = a + " " * (m+1) + w
else:
a = a + " " * m + w
n -= 1
ans.append(a)
# 处理最后一行
items = res[-1]
a = items[0]
for w in items[1:]:
a += (" " + w)
a = a + (" " * (maxWidth - len(a)))
ans.append(a)
return ans
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END