• leetCode题解之根据字符出现的频率排序


    1、题目描述

         

    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.


    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.

    题目意思是将一个输入string,按照其中每个字符出现的 频率进行重新排序,频率高的排在前面,频率低的排在后面,出现次数相同的则不做要求。

    2、问题分析
    统计字符串中每一个字符出现的次数,一般都会使用 hash 表的方法。本题中首先使用一个 无序的 unordered_map 将 每个字符出现的次数统计出来,
    想对字符按照顺序排序有多种方法,我选择使用 multimap 的方法,这个 hasp表的优点在于,key 可以重复出现,而且是根据键的值自动进行排序的。
    思路是将第一步得到的 unordered_map 中的每一项,将key 和 value 换个位置,这样得到的multimap 就是自动排好序的。然后对 multimap 进行输出,拼接成字符串,最后对字符串使用 reserve()方法即可。

    3、代码

     1  unordered_map<char,int>  m;
     2         
     3         for(  auto &c : s )
     4             m[c]++;
     5         
     6         multimap<int ,char> m1;
     7         
     8         
     9         for( auto& itr : m)
    10         {
    11             m1.insert( make_pair(itr.second,itr.first) );
    12         }
    13         
    14         string s_out;
    15         for(auto& itr :m1)
    16         {
    17             int n = itr.first ;
    18             while(n)
    19             {
    20                 s_out.push_back(itr.second);
    21                 n--;
    22             }
    23                 
    24         }
    25       
    26         reverse(s_out.begin(), s_out.end());
    27         return s_out;
    28 }


    pp
  • 相关阅读:
    SQL Server 2000 Windows CE Edition 2.0
    VC中ADO连接SQLSERVER的几种标准方式?
    VS.net 2010 F#
    几何向量gcd+暴力枚举——cf552
    函数的调用规则(__cdecl,__stdcall,__fastcall,__pascal)
    ALE IDocBDOC和IDOC的区别
    ABAPHow to use MS Word as editot in SAPscript and Smart Forms
    BISAP BI的权限管理
    CONote 74486 INFO: Overview of consulting notes for COPA
    ABAP 3D Graphs with SAP
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/8659863.html
Copyright © 2020-2023  润新知