2025-08-09 13:31:49 +0000 UTC

Rearrange Spaces Between Words

Code

class Solution:
    def reorderSpaces(self, text: str) -> str:
        res = []
        cur_word = []
        space_count = 0
        for char in text:
            if char == " ":
                space_count += 1
                if cur_word:
                    res.append("".join(cur_word))
                    cur_word.clear()
            else:
                cur_word.append(char)
        if cur_word:
            res.append("".join(cur_word))
        words = len(res) - 1
        if words == 0:
            join_str = ""
            rem_str = " " * space_count
        else:
            join_str = " " * (space_count // words) 
            rem_str = " " * (space_count % words)
        return "".join((join_str.join(res), rem_str))