华为实习生机试

一共三道题目,都比较简单。

  • 第一道忘了,考察vector的用法
  • 第二道考察map的用法,主要是排序
  • 第三道并查集

除了第三道不知道为啥没有A出来,其中第二道考察了map如何排序,还是比较不错的。
输入字符串,最后输出每个字母出现的次数。如果不是字母不统计。最后按照出现的次数进行从大到小排序,如果次数相同,谁先出现在字符串里面就排在前面。
map是没法直接排序的,它是由pair组成的,我们定义一个pair类型,再把这些pair放到vector里面进行sort排序。

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

const int maxn = 111;
map <char,int> dic;
typedef pair<char,int> pp;//定义pair
vector <pp> boom;
map <char,int> ran;//字符出现的先后顺序

bool cmp(pp a,pp b)
{
    if(a.second==b.second)
        return (ran[a.first]<ran[b.first]);
    else
        return a.second>b.second;

}

int main()
{
    char zz[maxn];
    int i,j,k,len;
    scanf("%s",zz);
    len = strlen(zz);
    for(i=0;i<len;i++)
    {
        if((zz[i]>='a'&&zz[i]<='z')||(zz[i]>='A'&&zz[i]<='Z'))
        {
            if(dic.count(zz[i])){
                dic[zz[i]]+=1;
            } else{
                dic[zz[i]]=1;
                ran[zz[i]]=i;
            }
        }

    }
    for(map<char,int>::iterator pointer=dic.begin();pointer!=dic.end();pointer++)
        boom.push_back(make_pair(pointer->first,pointer->second));//放进vector里面
    sort(boom.begin(),boom.end(),cmp);

    for(i=0;i<boom.size();i++)
        printf("%c=%d\n",boom[i].first,boom[i].second);
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值