LeetCode 1592: Rearrange Spaces Between Words
Problem Description
Explanation
To solve this problem, we need to count the total number of spaces and words in the given text. Then we can calculate the number of spaces to be placed between each pair of adjacent words by dividing the total number of spaces by the number of gaps between words. If there are any extra spaces, we distribute them evenly starting from the leftmost gap. Finally, we construct the rearranged string by adding words and spaces according to the calculated distribution.
- Time complexity: O(n), where n is the length of the input text.
- Space complexity: O(n), for storing the rearranged string.
Solutions
class Solution {
public String reorderSpaces(String text) {
int totalSpaces = 0;
int totalWords = 0;
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
if (c == ' ') {
totalSpaces++;
}
}
String[] words = text.trim().split("\\s+");
totalWords = words.length;
int spacesBetween = totalWords > 1 ? totalSpaces / (totalWords - 1) : 0;
int extraSpaces = totalWords > 1 ? totalSpaces % (totalWords - 1) : totalSpaces;
for (String word : words) {
result.append(word);
if (totalWords > 1 && extraSpaces > 0) {
for (int i = 0; i < spacesBetween; i++) {
result.append(' ');
}
extraSpaces--;
}
if (totalWords > 1 && extraSpaces == 0) {
for (int i = 0; i < spacesBetween; i++) {
result.append(' ');
}
}
}
for (int i = 0; i < extraSpaces; i++) {
result.append(' ');
}
return result.toString();
}
}
Loading editor...