【LeetCode】1592. 重新排列单词间的空格

题目

1592. 重新排列单词间的空格

给你一个字符串 text ,该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。题目测试用例保证 text 至少包含一个单词

请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能 最大化 该数目。如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,这也意味着返回的字符串应当与原 text 字符串的长度相等。

返回 重新排列空格后的字符串

示例 1:

输入:text = "  this   is  a sentence "
输出:"this   is   a   sentence"
解释:总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间,相邻单词间空格数为:9 / (4-1) = 3 个。

示例 2:

输入:text = " practice   makes   perfect"
输出:"practice   makes   perfect "
解释:总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。

示例 3:

输入:text = "hello   world"
输出:"hello   world"

示例 4:

输入:text = "  walks  udp package   into  bar a"
输出:"walks  udp  package  into  bar  a "

示例 5:

输入:text = "a"
输出:"a"

提示:

  • 1 <= text.length <= 100
  • text 由小写英文字母和 ' ' 组成
  • text 中至少包含一个单词

思路

  • 遍历字符串,解析所有的单词及空格数
  • 重新拼接单词和空格

代码

class Solution:
    def reorderSpaces(self, text: str) -> str:
        wordCount,spaceCount = 0,0
        i = 0
        words = []
        while i<len(text):
            while i<len(text) and text[i] == " ":
                spaceCount += 1
                i+=1
            if i<len(text) and text[i] != " ":
                wordCount += 1
                j = i
                while j<len(text) and text[j] != " ":
                    j+=1

                words.append(text[i:j])
                i = j
        sb = []
        for word in words[:-1]:
            sb.append(word)
            sb.append(" " * (spaceCount//(len(words)-1)))
            

        sb.append(words[-1])
        sb.append(" " * (spaceCount%(len(words)-1))) if len(words)>1 else sb.append(" " * spaceCount)
        return "".join(sb)

复杂度

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pass night

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值