[LeetCode] Sort Characters By Frequency 根据字符出现频率排序

 

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

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:app

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:post

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放到优先队列里排好序后,再取出来组成结果res便可,参见代码以下:url

 

解法一:spa

class Solution {
public:
    string frequencySort(string s) {
        string res = "";
        priority_queue<pair<int, char>> q;
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        for (auto a : m) q.push({a.second, a.first});
        while (!q.empty()) {
            auto t = q.top(); q.pop();
            res.append(t.first, t.second);
        }
        return res;
    }
};

 

咱们也可使用STL自带的sort来作,关键就在于重写comparator,因为须要使用外部变量,记得中括号中放入&,而后咱们将频率大的返回,注意必定还要处理频率相等的状况,要否则两个频率相等的字符可能穿插着出如今结果res中,这样是不对的。参见代码以下:code

 

解法二:htm

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> m;
        for (char c : s) ++m[c];
        sort(s.begin(), s.end(), [&](char& a, char& b){
            return m[a] > m[b] || (m[a] == m[b] && a < b);
        });
        return s;
    }
};

 

咱们也能够不使用优先队列,而是创建一个字符串数组,由于某个字符的出现次数不可能超过s的长度,因此咱们将每一个字符根据其出现次数放入数组中的对应位置,那么最后咱们只要从后往前遍历数组全部位置,将不为空的位置的字符串加入结果res中便可,参见代码以下:blog

 

解法三:排序

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

 

相似题目:

Top K Frequent Words

First Unique Character in a String

 

参考资料:

https://leetcode.com/problems/sort-characters-by-frequency/description/

https://leetcode.com/problems/sort-characters-by-frequency/discuss/93404/c-on-solution-without-sort

https://leetcode.com/problems/sort-characters-by-frequency/discuss/93409/concise-c-solution-using-stl-sort

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索