C++ Sorting by value in a map easy solution


  • 0
    A
    template<typename T1,typename T2>
    class Comparator {	
    public:
        bool operator ()(const std::pair<T1, T2> &a, const std::pair<T1, T2> &b)       const {
    	      return a.second > b.second;
    	}
    };
    
    class Solution {
    public:
        string frequencySort(string str) {
            std::map<char, int> mp;
            std::string res;
            for (auto c : str) {
                mp[c]++;
            }
    
            std::vector<std::pair<char, int>> mapCopy(mp.begin(),mp.end());
            sort(mapCopy.begin(),mapCopy.end(),Comparator<char,int>());
    
            for (auto it : mapCopy) {
                for (int i = 0; i < it.second; i++) {
                    res.push_back(it.first);
                }
            }
    
            return res;  
        }
    };
    

Log in to reply
 

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