Rearrange Words in Sentence

mail@pastecode.io avatar
unknown
c_cpp
12 days ago
1.1 kB
2
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> st;
        int n = text.length();

        string a = "";
        int i = 0;
        while (i < n) {
            a = a + text[i];
            if (text[i] == ' ') {
                a.pop_back();
                st.push_back(a);
                a = "";
            }
            i++;
        }
        st.push_back(a);

        stable_sort(st.begin(), st.end(), cmp);

        
        st[0][0] = toupper(st[0][0]);

       
        for (int j = 1; j < st.size(); j++) {
            for (int k = 0; k < st[j].length(); k++) {
                st[j][k] = tolower((unsigned char)st[j][k]);
            }
        }

        string ans = "";
        int k = st.size();
        for (int j = 0; j < k; j++) {
            ans = ans + st[j];
            if (j != k - 1) {
                ans = ans + " ";
            }
        }
        return ans;
    }
};
Leave a Comment