File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments