1592. Rearrange Spaces Between Words

Description

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 space. It's guaranteed that text contains at least one word.

Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.

Return the string after rearranging the spaces.

 

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.

 

Constraints:

  • 1 <= text.length <= 100
  • text consists of lowercase English letters and ' '.
  • text contains at least one word.

Solutions

Solution 1

Python Code
1
2
3
4
5
6
7
8
class Solution:
    def reorderSpaces(self, text: str) -> str:
        cnt = text.count(' ')
        words = text.split()
        m = len(words) - 1
        if m == 0:
            return words[0] + ' ' * cnt
        return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m)

Java Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public String reorderSpaces(String text) {
        int cnt = 0;
        for (char c : text.toCharArray()) {
            if (c == ' ') {
                ++cnt;
            }
        }
        String[] words = text.split("\\s+");
        List<String> res = new ArrayList<>();
        for (String w : words) {
            if (!"".equals(w)) {
                res.add(w);
            }
        }
        int m = res.size() - 1;
        if (m == 0) {
            return res.get(0) + " ".repeat(cnt);
        }
        String ans = String.join(" ".repeat(cnt / m), res);
        ans += " ".repeat(cnt % m);
        return ans;
    }
}

Go Code
1
2
3
4
5
6
7
8
9
func reorderSpaces(text string) string {
	cnt := strings.Count(text, " ")
	words := strings.Fields(text)
	m := len(words) - 1
	if m == 0 {
		return words[0] + strings.Repeat(" ", cnt)
	}
	return strings.Join(words, strings.Repeat(" ", cnt/m)) + strings.Repeat(" ", cnt%m)
}

TypeScript Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function reorderSpaces(text: string): string {
    let count = 0;
    for (const c of text) {
        if (c === ' ') {
            count++;
        }
    }

    const words = text.trim().split(/\s+/g);
    const n = words.length;
    if (n === 1) {
        return words.join('') + ''.padStart(count);
    }

    const rest = count % (words.length - 1);
    const per = (count - rest) / (words.length - 1);
    return words.join(''.padStart(per)) + ''.padStart(rest);
}

Rust Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
impl Solution {
    fn create_spaces(n: usize) -> String {
        let mut res = String::new();
        for _ in 0..n {
            res.push(' ');
        }
        res
    }

    pub fn reorder_spaces(text: String) -> String {
        let count = {
            let mut res = 0;
            for c in text.as_bytes() {
                if c == &b' ' {
                    res += 1;
                }
            }
            res
        };

        let works = text.split_whitespace().collect::<Vec<&str>>();
        let n = works.len();
        if n == 1 {
            return works[0].to_string() + &Self::create_spaces(count);
        }
        works.join(&Self::create_spaces(count / (n - 1))) + &Self::create_spaces(count % (n - 1))
    }
}