Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 79234c9

Browse files
authoredMay 25, 2020
Create rearrange-words-in-a-sentence.cpp
1 parent 444d23a commit 79234c9

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
 

‎C++/rearrange-words-in-a-sentence.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
string arrangeWords(string text) {
7+
text.front() = tolower(text.front());
8+
stringstream ss(text);
9+
string word;
10+
map<int, string> lookup;
11+
while (ss >> word) {
12+
lookup[word.size()] += word + " ";
13+
}
14+
string result;
15+
for (const auto& [_, word]: lookup) {
16+
result += word;
17+
}
18+
result.pop_back();
19+
result.front() = toupper(result.front());
20+
return result;
21+
}
22+
};
23+
24+
// Time: O(nlogn)
25+
// Space: O(n)
26+
class Solution2 {
27+
public:
28+
string arrangeWords(string text) {
29+
text.front() = tolower(text.front());
30+
auto words = split(text, ' ');
31+
stable_sort(begin(words), end(words),
32+
[](const string &s1, const string &s2) {
33+
return s1.size() < s2.size();
34+
});
35+
string result;
36+
for (const auto& word : words) {
37+
result += word + " ";
38+
}
39+
result.pop_back();
40+
result.front() = toupper(result.front());
41+
return result;
42+
}
43+
44+
private:
45+
vector<string> split(const string& s, const char delim) {
46+
vector<string> result;
47+
auto end = string::npos;
48+
do {
49+
const auto& start = end + 1;
50+
end = s.find(delim, start);
51+
result.emplace_back(s.substr(start, end - start));
52+
} while (end != string::npos);
53+
return result;
54+
}
55+
};

0 commit comments

Comments
 (0)
Please sign in to comment.