728x90
문제 : https://leetcode.com/problems/rearrange-spaces-between-words/description/
Rearrange Spaces Between Words - LeetCode
Can you solve this real interview question? Rearrange Spaces Between Words - 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 spa
leetcode.com
난이도 : 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