华为机试 — 字符统计

 1、字符统计

如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。

实现以下接口:
    输入一个字符串,对字符中的各个英文字符,数字,空格进行统计(可反复调用
    按照统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASII码由小到大排序输出
    清空目前的统计结果,重新统计
调用者会保证:输入的字符串以‘\0’结尾。

输入描述:输入一串字符。

输出描述:对字符中的各个英文字符(大小写分开统计),数字,空格进行统计,并按照统计个数由多到少输出,如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。

输入例子:aadddccddc

输出例子:dca

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include <vector>
#include<string>
#include<map>
using namespace std;

//先比较第二个字符,在第二个字符相同的时候比较第一个字符
bool cmp(const pair<char, int> a, const pair<char, int> b) {
    if (a.second != b.second) return a.second>b.second;
    else
        return a.first < b.first;
}

int main()
{
    string str;
    while (cin >> str)
    {
        map<char, int> strmap;
        for (int i = 0; i < str.size(); ++i)
        {
            if (!strmap.count(str[i]))
            {
                strmap[str[i]] = 1;
            }
            else
            {
                strmap[str[i]]++;
            }    
        }
        //将保存到map中的数据转存到vector中
        vector<pair<char, int>> strvec(strmap.begin(), strmap.end());
        sort(strvec.begin(), strvec.end(), cmp);
        for (int i = 0; i < strvec.size(); ++i)
        {
            cout << strvec[i].first << endl;
        }
    }

    system("pause");
    return 0;
}

 

posted @ 2018-08-12 10:13  深度机器学习  阅读(702)  评论(0编辑  收藏  举报