LeetCode #451 - Sort Characters By Frequency

题目描述:

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.

对于一个字符串,按照字符的频率排序。将字符和字符的频率组成pair,然后按照频率进行排序,进而构造新的字符串。

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char,int> hash;
        for(int i=0;i<s.size();i++) 
        {
            if(hash.count(s[i])==0) hash[s[i]]=1;
            else hash[s[i]]++;
        }
        vector<pair<char,int>> count;
        for(unordered_map<char,int>::iterator it=hash.begin();it!=hash.end();it++)
            count.push_back(pair<char,int>((*it).first,(*it).second)); 
        sort(count.begin(),count.end(),comp);
        
        string result;
        for(int i=0;i<count.size();i++)
        {
            for(int j=0;j<count[i].second;j++) 
                result+=count[i].first;
        }
        return result;
    }             
                            
    static bool comp(pair<char,int> a, pair<char,int> b)
    {
        if(a.second>=b.second) return true;
        else return false;
    }
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/81254535