Leetcode 1592. Rearrange Spaces Between Words
You are given a string text
of words that are separated by spaces. Your task is to rearrange the spaces so that there is an equal number of spaces between each word and any extra spaces are placed at the end of the string.
For instance, consider the input string text = " this is a sentence "
.
"this"
, "is"
, "a"
, and "sentence"
.Your task is to partition the spaces as evenly as possible between the words, with any extra spaces flowing to the end.
Input: text = " this is a sentence "
Output: "this is a sentence"
1 <= text.length <= 100
text
consists of lowercase and uppercase English letters and ‘ ‘ (space) characters.text
.evenlyDistributedSpaces
).remainingSpaces
).Here’s the complete implementation in Java:
public class Solution {
public String reorderSpaces(String text) {
// Split the text by spaces to get words
String[] words = text.trim().split("\\s+");
int totalSpaces = text.length() - text.replace(" ", "").length();
int spaceBetweenWords = words.length > 1 ? totalSpaces / (words.length - 1) : 0;
int extraSpaces = words.length > 1 ? totalSpaces % (words.length - 1) : totalSpaces;
// Join words with `spaceBetweenWords` number of spaces.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) {
for (int j = 0; j < spaceBetweenWords; j++) {
sb.append(' ');
}
}
sb.append(words[i]);
}
// Add extra spaces at the end
for (int i = 0; i < extraSpaces; i++) {
sb.append(' ');
}
return sb.toString();
}
}
O(n)
where n
is the length of the input string.O(n)
where n
is the length of the input string.O(n)
where n
is the length of the original input string (since we iterate over words and the spaces).Therefore, the overall time complexity is O(n)
, where n
is the length of the input string.
This is efficient given the constraint that the maximum length of text
can be 100 characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?