LeetCode 1592: Rearrange Spaces Between Words Solution
Master LeetCode problem 1592 (Rearrange Spaces Between Words), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1592. Rearrange Spaces Between Words
Problem Explanation
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.
Solution Code
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();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1592 (Rearrange Spaces Between Words)?
This page provides optimized solutions for LeetCode problem 1592 (Rearrange Spaces Between Words) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1592 (Rearrange Spaces Between Words)?
The time complexity for LeetCode 1592 (Rearrange Spaces Between Words) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1592 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1592 in Java, C++, or Python.