5519. 重新排列单词间的空格
传送门
[传送门]()
题意
结题思路
# 思路1:
# 遍历字符串,查询其有n个空格,k个单词,这些空格的数量要插在k-1个位置中。剩余的余数放在最末尾,返回重新排列空格后的字符串。
# 总结:
# count():返回字符串中某字符数量
# divmod():返回商和余数
# join():在一列list的每个元素后面连接前面的变量
class Solution(object):
def reorderSpaces(self, text):
"""
:type text: str
:rtype: str
"""
space_count = text.count(' ')
list1 = text.strip().split()
if len(list1) == 1:
return list1[0] + ' ' * space_count
k1, k2 = divmod(space_count, len(list1) - 1)
return (' ' * k1).join(list1) + ' ' * k2