68. 文本左右对齐 - 力扣(LeetCode)
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
result = []
current_line = []
current_length = 0
for word in words:
# 如果当前行加上这个单词后超过 maxWidth,则需要处理当前行
if current_length + len(word) + len(current_line) > maxWidth:
# 计算当前行的空格数量
spaces_needed = maxWidth - current_length
if len(current_line) == 1:
# 如果当前行只有一个单词,直接把剩余空格添加到单词后面
result.append(current_line[0] + ' ' * spaces_needed)
else:
# 计算空格分配
spaces_between_words = spaces_needed // (len(current_line) - 1)
extra_spaces = spaces_needed % (len(current_line) - 1)
line = current_line[0]
for i in range(1, len(current_line)):
# 加上均匀的空格
line += ' ' * (spaces_between_words + (1 if i <= extra_spaces else 0)) + current_line[i]
result.append(line)
# 重置当前行
current_line = [word]
current_length = len(word)
else:
# 如果没有超出,则继续将单词加入当前行
current_line.append(word)
current_length += len(word)
# 处理最后一行:左对齐且单词间有单个空格,剩余空格补充在末尾
last_line = ' '.join(current_line)
result.append(last_line + ' ' * (maxWidth - len(last_line)))
return result