Easy to understand C++ using sorted vector

  • 0

    The largest alphabetical character value is 'z' = 122, so create a vector of size 123 in order to fit each character into its ordinal index. 'A' = 65, 'a' = 97, etc.

    Append each character in the input string onto its corresponding index.
    For example:

    If the input is "zAaAa", then:
    alpha_group[65] = "AA"
    alpha_group[97] = "aa"
    alpha_group=[122] = "z"

    Sort vector in decreasing order by the string size, then add non-empty strings onto the end result in this order.

    class Solution{
        string frequencySort(string s){
            string res;
            vector<string> alpha_group(123);
            for (char c : s){
                alpha_group[ int(c) ] += c;
            sort(alpha_group.begin(), alpha_group.end(),
                 [](string& a, string& b){ return a.size() > b.size(); });
            for (auto group : alpha_group){
                if (!group.empty()) { res += group; }
            return res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.