728x90
문제 : https://leetcode.com/problems/rearrange-spaces-between-words/description/
난이도 : Easy
풀이
class Solution:
def reorderSpaces(self, text: str) -> str:
spaces = text.count(' ') # 빈칸 수
words = text.split() # 단어 분리
wordsCnt = len(words) # 단어 갯수
rearrangeSpaces = 0 if wordsCnt == 1 else spaces//(wordsCnt- 1) # 재정렬할 빈칸 수
trailingSpaces = spaces - rearrangeSpaces * (wordsCnt - 1) # 단어 끝에 올 빈칸 수
return (' ' * rearrangeSpaces).join(words) + ' ' * trailingSpaces
728x90