forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRearrange Spaces Between Words.cpp
46 lines (37 loc) · 1.11 KB
/
Rearrange Spaces Between Words.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Runtime: 4 ms (Top 33.02%) | Memory: 6.1 MB (Top 81.73%)
class Solution {
public:
string reorderSpaces(string text) {
int ct=0;
// Collection of words
vector<string> v;
for (int i=0; i<text.size(); i++){
// Calculate the numbert of spaces
while(i<text.size() && text[i] == ' '){
ct++;
i++;
}
// Extract the words and collect them
string tp="";
while(i<text.size() && text[i] != ' '){
tp+=text[i];
i++;
}
i--;
// Adding word to the collection
if(tp.size()) v.push_back(tp);
}
text = "";
// Combining the words with equal number of white spaces
for(int i=0; i<v.size()-1; i++){
text += v[i];
int j=ct/(v.size()-1);
while(j--) text += ' ';
}
text += v[v.size()-1];
// Adding remaining extra spaces at the end
int j=(v.size() > 1)?ct % (v.size()-1):ct;
while(j--) text += ' ';
return text;
}
};