1592. 重新排列单词间的空格 - 力扣(LeetCode)



可以分几个步骤来解决这个问题:
步骤说明:
-
统计空格数量。
-
提取所有单词。
-
计算每对单词之间应插入的空格数量。
-
构造最终字符串。
举个例子:
text = " this is a sentence "
-
单词有:["this", "is", "a", "sentence"]
-
空格数 = 9
-
单词数 = 4,单词之间有 3 个间隔
-
每个间隔可以放:9 // 3 = 3 个空格
-
剩下的空格 = 9 % 3 = 0
-
最终:
"this___is___a___sentence"(下划线代表空格)
Python代码如下:
def reorder_spaces(text: str) -> str:
# 统计空格数量
space_count = text.count(' ')
# 提取所有单词
words = text.split()
# 单词数量
num_words = len(words)
if num_words == 1:
# 只有一个单词,所有空格放到末尾
return words[0] + ' ' * space_count
# 平均每对单词间的空格数
spaces_between = space_count // (num_words - 1)
# 剩余空格
trailing_spaces = space_count % (num_words - 1)
# 用空格连接单词,并加上末尾多余的空格
return (' ' * spaces_between).join(words) + ' ' * trailing_spaces
你可以传入任意字符串运行看看效果,比如:
print(reorder_spaces(" hello world "))
# 输出: "hello world "
810

被折叠的 条评论
为什么被折叠?



