#1592

Rearrange Spaces Between Words

pupil · 520 · lc easy +28 · verified · 44.2% accepted · 491 likes · top 26%

Description

Given a string text containing words separated by spaces, redistribute all the spaces so that the gaps between adjacent words are as large and as equal as possible. Any leftover spaces go at the end. Return the reformatted string, which must have the same total length as text.

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.

Code

1
2
3