-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrearrangeSpacesBetweenWords.cpp
More file actions
38 lines (36 loc) · 990 Bytes
/
rearrangeSpacesBetweenWords.cpp
File metadata and controls
38 lines (36 loc) · 990 Bytes
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
// Source: https://leetcode.com/problems/rearrange-spaces-between-words/
// Author: Miao Zhang
// Date: 2021-05-19
class Solution {
public:
string reorderSpaces(string text) {
vector<string> words;
int spaces = 0;
string word;
for (char& c: text) {
if (c == ' ') {
spaces++;
if (word != "") {
words.push_back(word);
word = "";
}
} else {
word += c;
}
}
if (word != "") {
words.push_back(word);
}
int n = words.size();
if (n == 1) {
return words[0] + string(spaces, ' ');
}
string res;
int interval = spaces / (n - 1);
for (int i = 0; i < n; i++) {
res += (i != n - 1) ? (words[i] + string(interval, ' ')) : words[i];
}
res += string(spaces % (n - 1), ' ');
return res;
}
};