forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rearrange-words-in-a-sentence.cpp
55 lines (52 loc) · 1.45 KB
/
rearrange-words-in-a-sentence.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
47
48
49
50
51
52
53
54
55
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
string arrangeWords(string text) {
text.front() = tolower(text.front());
stringstream ss(text);
string word;
map<int, string> lookup;
while (ss >> word) {
lookup[word.size()] += word + " ";
}
string result;
for (const auto& [_, word]: lookup) {
result += word;
}
result.pop_back();
result.front() = toupper(result.front());
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
string arrangeWords(string text) {
text.front() = tolower(text.front());
auto words = split(text, ' ');
stable_sort(begin(words), end(words),
[](const string &s1, const string &s2) {
return s1.size() < s2.size();
});
string result;
for (const auto& word : words) {
result += word + " ";
}
result.pop_back();
result.front() = toupper(result.front());
return result;
}
private:
vector<string> split(const string& s, const char delim) {
vector<string> result;
auto end = string::npos;
do {
const auto& start = end + 1;
end = s.find(delim, start);
result.emplace_back(s.substr(start, end - start));
} while (end != string::npos);
return result;
}
};