Skip to content

1592. Rearrange Spaces Between Words

  • Time: $O(|\texttt{text}|)$
  • Space: $O(|\texttt{text}|)$
 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
class Solution {
 public:
  string reorderSpaces(string text) {
    const int spaces = ranges::count(text, ' ');
    string ans;
    vector<string> words;

    istringstream iss(text);
    string word;

    while (iss >> word)
      words.push_back(word);

    if (words.size() == 1)
      return word + string(spaces, ' ');

    const int gapSize = spaces / (words.size() - 1);
    const int remains = spaces % (words.size() - 1);

    for (int i = 0; i < words.size() - 1; ++i)
      ans += words[i] + string(gapSize, ' ');
    ans += words.back() + string(remains, ' ');

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public String reorderSpaces(String text) {
    final String[] words = text.trim().split("\\s+");
    final int spaces = (int) text.chars().filter(c -> c == ' ').count();
    final int n = words.length;
    final int gapSize = n == 1 ? 0 : spaces / (n - 1);
    final int remains = n == 1 ? spaces : spaces % (n - 1);
    return String.join(" ".repeat(gapSize), words) + " ".repeat(remains);
  }
}