欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > python-leetcode-文本左右对齐

python-leetcode-文本左右对齐

2025/5/23 18:55:31 来源:https://blog.csdn.net/Lucy_wzw/article/details/145003683  浏览:    关键词:python-leetcode-文本左右对齐

68. 文本左右对齐 - 力扣(LeetCode)

class Solution:def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:result = []current_line = []current_length = 0for word in words:# 如果当前行加上这个单词后超过 maxWidth,则需要处理当前行if current_length + len(word) + len(current_line) > maxWidth:# 计算当前行的空格数量spaces_needed = maxWidth - current_lengthif 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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词