Problem
Given a sentence text
(A sentence is a string of space-separated words) in the following format:
- First letter is in upper case.
- Each word in
text
are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
Return the new text following the format shown above.
Solution
Nothing too interesting to explain, makes me wonder why is problem is categorized as “medium”.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string arrangeWords(string text) {
map<int, string> m;
text[0] = tolower(text[0]);
stringstream ss(text);
string word, output;
while (ss >> word) m[word.size()] += word + " ";
for (const auto &pair: m) output += pair.second;
output.pop_back();
output[0] = toupper(output[0]);
return output;
}
};