1
class Solution {
2
public:
3
vector<pair<string, int>> words;
4
string arrangeWords(string text) {
5
// convert to lowercase alphabet
6
text[0] += 32;
7

8
istringstream iss(text);
9
string word = "";
10

11
// pos is the index of each word in text.
12
int pos = 0;
13

14
while (iss >> word) {
15
words.push_back({word, pos});
16
++pos;
17
}
18

19
// sort by length and pos.
20
sort(begin(words), end(words),
21
[&](const pair<string, int> &p1, const pair<string, int> &p2) -> bool {
22
if (size(p1.first) == size(p2.first)) return p1.second < p2.second;
23
return size(p1.first) < size(p2.first);
24
});
25

26
string ans = "";
27
for (auto &x : words) ans += x.first + " ";
28
ans.pop_back();
29

30
// convert to uppercase alphabet
31
ans[0] -= 32;
32
return ans;
33
}
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0