1
class Solution {
2
public:
3
string reorderSpaces(string text) {
4
int ct = 0;
5

6
// Collection of words
7
vector<string> v;
8
for (int i = 0; i < text.size(); i++) {
9
// Calculate the numbert of spaces
10
while (i < text.size() && text[i] == ' ') {
11
ct++;
12
i++;
13
}
14

15
// Extract the words and collect them
16
string tp = "";
17
while (i < text.size() && text[i] != ' ') {
18
tp += text[i];
19
i++;
20
}
21
i--;
22

23
// Adding word to the collection
24
if (tp.size()) v.push_back(tp);
25
}
26

27
text = "";
28

29
// Combining the words with equal number of white spaces
30
for (int i = 0; i < v.size() - 1; i++) {
31
text += v[i];
32
int j = ct / (v.size() - 1);
33
while (j--) text += ' ';
34
}
35

36
text += v[v.size() - 1];
37

38
// Adding remaining extra spaces at the end
39
int j = (v.size() > 1) ? ct % (v.size() - 1) : ct;
40
while (j--) text += ' ';
41

42
return text;
43
}
44
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0