Leetcode 1592. Rearrange Spaces Between Words
Given a string text
of words and spaces, rearrange the spaces such that:
Return the resultant string after redistribution.
text
consists of lowercase English letters and spaces.1 <= text.length <= 100
.text
.text
.Here’s the C++ code for solving the problem:
#include <iostream>
#include <vector>
#include <sstream>
std::string reorderSpaces(std::string text) {
int totalSpaces = 0, n = text.size();
for (char c : text) {
if (c == ' ')
totalSpaces++;
}
std::vector<std::string> words;
std::istringstream ss(text);
std::string word;
while (ss >> word) {
words.push_back(word);
}
int numWords = words.size();
if (numWords == 1) {
// Only one word, all spaces go at the end
return words[0] + std::string(totalSpaces, ' ');
} else {
int spacesBetween = totalSpaces / (numWords - 1);
int extraSpaces = totalSpaces % (numWords - 1);
std::string result;
for (int i = 0; i < numWords; i++) {
result += words[i];
if (i != numWords - 1) {
result += std::string(spacesBetween, ' ');
}
}
// Append the remaining spaces
result += std::string(extraSpaces, ' ');
return result;
}
}
N
is the length of the text
.
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?