451. Sort Characters By Frequency 堆

来源:互联网 发布:淘宝优惠劵是真的吗 编辑:程序博客网 时间:2024/05/22 15:57

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:"tree"Output:"eert"Explanation:'e' appears twice while 'r' and 't' both appear once.So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:"cccaaa"Output:"cccaaa"Explanation:Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:"Aabb"Output:"bbAa"Explanation:"bbaA" is also a valid answer, but "Aabb" is incorrect.

Note that 'A' and 'a' are treated as two different characters.

我的思路:

建立哈希数组统计字符出现次数,然后将其写到优先级队列中去,再一次打印堆顶元素。

class Solution {public:    string frequencySort(string s) {        vector<int> alp(256,0);        for(auto c:s)            alp[c]++;        priority_queue<pair<char,int>,vector<pair<char,int>>,comp> res;        for(int i=0;i<256;i++)        {            if(alp[i]>0)                res.emplace(i,alp[i]);        }        string s2;        while(!res.empty())        {            pair<char,int> temp=res.top();            res.pop();            int count=temp.second;            while(count--)            s2.push_back(temp.first);        }        return s2;    }    struct comp{      bool operator()(const pair<char,int>& a,const pair<char,int>& b){          return a.second<b.second;      }      };};
其他解法:

(1)使用unordered_map和数组

class Solution {public:    string frequencySort(string s) {        unordered_map<char,int> freq;        vector<string> bucket(s.size()+1, "");//建立一个string的vector,下标代表出现的次数        string res;                //使用哈希map统计单词频率        for(char c:s) freq[c]++;        //        for(auto& it:freq) {            int n = it.second;            char c = it.first;            bucket[n].append(n, c);//对于出现为n次的子母,在相应的string后面添加        }        //        for(int i=s.size(); i>0; i--) {            if(!bucket[i].empty())                res.append(bucket[i]);        }        return res;    }};



原创粉丝点击