zoukankan      html  css  js  c++  java
  • 451、根据字符出现频率排序(哈希 加优先队列)

    给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

    示例 1:

    输入:
    "tree"

    输出:
    "eert"

    解释:
    'e'出现两次,'r'和't'都只出现一次。
    因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
    示例 2:

    输入:
    "cccaaa"

    输出:
    "cccaaa"

    解释:
    'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
    注意"cacaca"是不正确的,因为相同的字母必须放在一起。
    示例 3:

    输入:
    "Aabb"

    输出:
    "bbAa"

    解释:
    此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
    注意'A'和'a'被认为是两种不同的字符。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/sort-characters-by-frequency
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 //优先队列 大顶堆实现 90% 
     4 class Solution {
     5 public:
     6     struct Cell
     7     {
     8         char c;
     9         int frequency;
    10         Cell(char ch, int freq):c(ch), frequency(freq) {};
    11         friend bool operator <(Cell c1, Cell c2)
    12         {
    13             if (c1.frequency == c2.frequency)
    14                 return c1.c > c2.c;
    15             else
    16                 return c1.frequency < c2.frequency;
    17         }
    18     };
    19     string frequencySort(string s) {
    20         map<char, int> hash;
    21         priority_queue<Cell> que;
    22         int len = s.length();
    23         for (int i = 0; i < len; i++)
    24             hash[s[i]]++;
    25         for (auto item : hash)
    26             que.push({ item.first, item.second });
    27         string res = "";
    28         while (!que.empty())
    29         {
    30             auto p = que.top();
    31             que.pop();
    32             for (int i = 0; i < p.frequency; i++)
    33                 res += p.c;
    34         }
    35         return res;
    36     }
    37 };
    38 int main()
    39 {
    40     string s;
    41     cin >> s;
    42     cout << Solution().frequencySort(s);
    43     return 0;
    44 }
  • 相关阅读:
    MySQL 中视图和表的区别以及联系是什么?
    MAC将根目录文件夹的权限赋给用户
    PHP 基础篇 PHP 中 DES 加解密详解
    软件构架师必修科(转)
    遍历指定文件夹下所有的xml文件并动态生成HTML页面!
    使用XML创建Excel文档
    XmlTextWriter创建XML文件
    什么是耦合?
    JavaScript经典效果集锦(一)
    软件最大的追求是什么?
  • 原文地址:https://www.cnblogs.com/lancelee98/p/13453855.html
Copyright © 2011-2022 走看看