Simple C++ (13ms) LAMBDA sort solution (beats 88% submission)


  • 0
    M
    string frequencySort(string s) {
            if (s.empty())
                return "";
            
            //populate map with chars and their # of occurence
            map<char,int> myMap;
            for (auto c : s)
                myMap[c]++;
            
            //store each char (by # of occurences) in a vector of strings
            vector<string> sVec;
            sVec.reserve(s.size());
            for (auto c : myMap){
                sVec.push_back(string(c.second, c.first));
            }
            
            //passing a lambda argument sort vector based on length of strings 
            sort(sVec.begin(), sVec.end(), [](const string& a, const string& b){
                    return a.size() > b.size();
                });
            
            //populate return string
            string ret = "";
            for(auto it = sVec.begin(); it != sVec.end(); ++it)
                ret.append(*it);
            return ret;
    
        }
    

Log in to reply
 

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