Rearrange Words in Sentence [Accepted]

mail@pastecode.io avatar
unknown
c_cpp
14 days ago
889 B
3
Indexable
Never
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;
    }
};
Leave a Comment