Skip to content

Latest commit

 

History

History
32 lines (30 loc) · 875 Bytes

1592.md

File metadata and controls

32 lines (30 loc) · 875 Bytes

5519. Rearrange Spaces Between Words

Solution 1

class Solution(object):
    def reorderSpaces(self, text):
        """
        :type text: str
        :rtype: str
        """
        words = text.strip().split()
        num_words = len(words)
        num_spaces = 0
        for i in range(len(text)):
            if text[i] == " ":
                num_spaces += 1
        if num_spaces == 0:
            return text
        if num_words == 1:
            return words[0] + " " * num_spaces
        mid_spaces = num_spaces // (num_words - 1)
        final_spaces = num_spaces % (num_words - 1)
        new_text = ""
        for i in range(len(words)):
            new_text += words[i]
            if i == len(words) - 1:
                new_text += " " * final_spaces
            else:
                new_text += " " * mid_spaces
        return new_text