[Huawei] machine test 108 title character counts

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011544909/article/details/79999194

Description Title
If the count number of the same, according to the ascending sort output ASII code. If there are other characters, these characters do not have statistics.

Implement the following interfaces:
input a string of characters in each of English characters, numbers, spaces statistics (which may be called repeatedly)
in accordance with the number of the output count from more to less statistical results, if the same number of statistics, in accordance with the code ASII ascending sort output
to clear the current statistics, recount
the caller will ensure that:
the input string ends with '\ 0'.

Input Description:
Enter a string of characters.

Output Description: The
character of
each of English characters (case separate), numbers, spaces statistics, and in accordance with the number of outputs from more to less statistics, if the count number of the same, according to the ascending sort code ASII output. If there are other characters, these characters do not have statistics.

Example 1
Input
aadddccddc
output
dca


Ideas: we can use the map to count the number of the corresponding character, since map is a nonlinear structure, can not be directly sorted, so we put it into the vector, and then define the cmp function to sort them.
Because the container default map are sorted in ascending order of the key values, so that if the number can be two characters are the same, the former effect ascii code of a small output.
Here stable_sort function we use, the advantages of this function is that if two numbers are the same, do not change their relative positions.


#include <bits/stdc++.h>
using namespace std;

bool cmp(pair<char,int> a,pair<char,int> b)
{
    return a.second > b.second;
}

int main()
{
    string str;
    while(getline(cin,str))
    {
        map<char,int>m;
        for(int i=0;i<str.size();i++)
            m[str[i]]++;
        vector<pair<char,int>>v (m.begin(),m.end());
        stable_sort(v.begin(),v.end(),cmp);
        for(auto &p:v)
            cout<<p.first;
        cout<<endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/u011544909/article/details/79999194