Rearrange Words in Sentence [Accepted]
unknown
c_cpp
2 years ago
889 B
6
Indexable
bool cmp(string a, string b) {
if (a.length() == b.length()) {
return false;
}
return a.length() < b.length();
}
class Solution {
public:
string arrangeWords(string text) {
vector<string> v;
int n = text.length();
string curr = "";
for(int i = 0; i < text.length(); i++) {
if(text[i] == ' ') {
v.push_back(curr);
curr = "";
}
else {
text[i] = tolower(text[i]);
curr += text[i];
}
}
v.push_back(curr);
stable_sort(v.begin(), v.end(), cmp);
v[0][0] = toupper(v[0][0]);
string ans = "";
for(int i = 0; i < v.size(); i++) {
ans += v[i];
if(i != v.size() - 1) ans += ' ';
}
return ans;
}
};
Editor is loading...
Leave a Comment