leetcode 1592. Rearrange Spaces Between Words(python)

277 阅读1分钟

这是我参与更文挑战的第8天,活动详情查看: 更文挑战

描述

You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.

Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.

Return the string after rearranging the spaces.

Example 1:

Input: text = "  this   is  a sentence "
Output: "this   is   a   sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.	

Example 2:

Input: text = " practice   makes   perfect"
Output: "practice   makes   perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.

Example 3:

Input: text = "hello   world"
Output: "hello   world"

Example 4:

Input: text = "  walks  udp package   into  bar a"
Output: "walks  udp  package  into  bar  a "

Example 5:

Input: text = "a"
Output: "a"

Note:

1 <= text.length <= 100
text consists of lowercase English letters and ' '.
text contains at least one word.

解析

根据题意,就是找出空格,可以尽量均分到单词中间,如果有多出来的空格则放到字符串最后。思路很简单如果没有空格则直接返回 text ;如果有空格且只有一个单词,则将空格全部追加到单词后面返回;其他情况则直接将空格均分到单词中间,有多出来的直接追加到结果之后就可以得到结果。

解答

class Solution(object):
    def reorderSpaces(self, text):
        """
        :type text: str
        :rtype: str
        """
        c = collections.Counter(text)
        if c[' ']==0:
            return text
        split_text = text.split()
        N = len(split_text)
        a = c[' ']
        b = N - 1
        if b==0:
            return split_text[0]+' '*c[' ']
        span = a // b
        r = ''
        for i in range(N):
            if i!=N-1:
                r += split_text[i]+(' '*span)
                c[' '] -= span
            else:
                r += split_text[i]
        if c[' ']>0:
            r += ' '*c[' ']
        return r
        	      
		

运行结果

Runtime: 12 ms, faster than 93.39% of Python online submissions for Rearrange Spaces Between Words.
Memory Usage: 13.4 MB, less than 71.07% of Python online submissions for Rearrange Spaces Between Words.

原题链接:leetcode.com/problems/re…

您的支持是我最大的动力