Formatted question description: https://leetcode.ca/all/1592.html

1592. Rearrange Spaces Between Words (Easy)

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.


Example 3:

Input: text = "hello   world"
Output: "hello   world"


Example 4:

Input: text = "  walks  udp package   into  bar a"
Output: "walks  udp  package  into  bar  a "


Example 5:

Input: text = "a"
Output: "a"


Constraints:

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

Related Topics:
String

Similar Questions:

Solution 1.

• class Solution {
public String reorderSpaces(String text) {
List<String> wordsList = new ArrayList<String>();
int spaces = 0;
StringBuffer sb = new StringBuffer();
int length = text.length();
for (int i = 0; i < length; i++) {
char c = text.charAt(i);
if (c == ' ') {
spaces++;
if (sb.length() > 0) {
sb.setLength(0);
}
} else
sb.append(c);
}
if (sb.length() > 0)
StringBuffer reorder = new StringBuffer();
int size = wordsList.size();
if (size == 1) {
reorder.append(wordsList.get(0));
for (int i = 0; i < spaces; i++)
reorder.append(' ');
return reorder.toString();
}
int spacesEach = spaces / (size - 1);
int remain = spaces % (size - 1);
for (int i = 0; i < size; i++) {
if (i > 0) {
for (int j = 0; j < spacesEach; j++)
reorder.append(' ');
}
reorder.append(wordsList.get(i));
}
for (int i = 0; i < remain; i++)
reorder.append(' ');
return reorder.toString();
}
}

############

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)) {
}
}
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;
}
}

• // OJ: https://leetcode.com/problems/rearrange-spaces-between-words/
// Time: O(N)
// Space: O(N)
class Solution {
public:
string reorderSpaces(string s) {
int N = s.size(), cnt = 0;
for (char c : s) cnt += c == ' ';
string word;
istringstream ss(s);
vector<string> words;
while (ss >> word) words.push_back(word);
string ans;
if (words.size() == 1) {
ans += words[0];
for (int i = 0; i < cnt; ++i) ans += ' ';
return ans;
}
int d = cnt / (words.size() - 1), r = cnt - d * (words.size() - 1);
for (int i = 0; i < words.size(); ++i) {
ans += words[i];
int e = i < words.size() - 1 ? d : r;
for (int k = 0; k < e; ++k) ans += ' ';
}
return ans;
}
};

• 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)

############

# 1592. Rearrange Spaces Between Words
# https://leetcode.com/problems/rearrange-spaces-between-words/

class Solution:
def reorderSpaces(self, text: str) -> str:
texts = text.split()
spaces = 0

for i in text:
if i == " ":
spaces += 1
if len(texts) == 1:
return texts[0] + " " * spaces

between = spaces // (len(texts)-1)
leftover = spaces % (len(texts)-1)

return (" " * between).join(texts) + " "*leftover

• 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)
}

• 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) {
}

const rest = count % (words.length - 1);
const per = (count - rest) / (words.length - 1);
}


• 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))
}
}