[LeetCode] Rearrange Words in a Sentence

1451. Rearrange Words in a Sentence

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
string arrangeWords(string text) {
text[0] = tolower(text[0]);
text.push_back(' ');
string now = "";
map<int, vector<string>> mp;
for(int i = 0; i < text.length(); i++) {
if(text[i] == ' ') {
mp[now.length()].push_back(now);
now = "";
} else now.push_back(text[i]);
}
string res = "";
for(auto& [_, v] : mp) {
for(auto& w : v) {
res += w + " ";
}
}
res.pop_back();
res[0] = toupper(res[0]);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/19/PS/LeetCode/rearrange-words-in-a-sentence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.