LeetCode - Sort Characters By Frequency

解法一:

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> temp;
        vector<vector<char>> bucket(s.size()+1);
        string res="";
        for(int i=0;i<s.size();i++){
            temp[s[i]]++;
        }
        for(auto a: temp){
            bucket[a.second].push_back(a.first);
        }
        for(int i=s.size();i>=0;i--){
            for(auto a:bucket[i]){
                for(int j=0;j<i;j++) res+=a;
            }
        }
        return res;
    }
};

解法二:

class Solution {
public:
    string frequencySort(string s) {
        string res="";
        unordered_map<char, int> temp;
        for(int i=0;i<s.size();i++) temp[s[i]]++;
        sort(s.begin(), s.end(), [&](const char& a, const char& b){
            return (temp[a]>temp[b] || (temp[a]==temp[b] && a<b ));
        });
        return s;
    }
};

解法三:

class Solution {
public:
    string frequencySort(string s) {
        string res="";
        unordered_map<char, int> temp;
        for(int i=0;i<s.size();i++) temp[s[i]]++;
        vector<string> m(s.size()+1, "");
        for(auto a:temp){
            for(int i=0;i<a.second;i++) m[a.second] += a.first;
        }
        for(int i=s.size();i>=0;i--) res += m[i];
        return res;
    }
};

解法一、二,一个是用priority_queue, 另一个是sort,都是O(N logN),解法三用了桶排序,只需要O(N)

Error

class Solution {
public:
    bool myfunc(char& a, char& b){
        return (temp[a]>temp[b] || (temp[a]==temp[b] && a<b ));
    }
    string frequencySort(string s) {
        string res="";
        for(int i=0;i<s.size();i++) temp[s[i]]++;
        sort(s.begin(), s.end(), myfunc);
        return s;
    }
private:
    unordered_map<char, int> temp;
};
Line 9: invalid use of non-static member function 'bool Solution::myfunc(char&, char&)'

ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/82655337