浙大 PAT 甲级 1071 Speech Patterns map的自定义排序 字符处理

本题考查字符处理,包括对单词的理解,是很常见的一道题。很容易想到用map存储,找到数量最多、单词词典顺序较小的那个词需要用到map的自定义排序。

map的自定义排序是通过将map转换成vector<pair<temp1 temp2>>,然后使用sort函数处理的。关于map的排序可以参看

https://blog.csdn.net/weixin_34212189/article/details/85584916

写的比较详细和全面。

下面贴出AC代码

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

bool cmp(pair<string, int> a, pair<string, int> b)
{
    if (a.second != b.second)
    {
        return (a.second > b.second);
    }
    else
    {
        return (a.first < b.first);
    }
}

int main()
{
    map<string, int> words;
    char c;
    string word;
    while (scanf("%c", &c))
    {
        if ((c >= '0'&&c <= '9') || (c >= 'a'&&c <= 'z') || (c >= 'A'&&c <= 'Z'))
        {
            // 全部转换成小写来存储
            if (c >= 'A'&&c <= 'Z')
            {
                c = 'a' + c - 'A';
            }
            word += c;
        }
        else
        {
            if (word.size() != 0)
            {
                if (words.count(word) == 0)
                {
                    words[word] = 1;
                }
                else
                {
                    words[word]++;
                }
                word.clear();
            }
            if (c == '\n')
            {
                break;
            }
        }
    }
    vector<pair<string, int>> wordVec(words.begin(), words.end());
    sort(wordVec.begin(), wordVec.end(), cmp);
    printf("%s %d\n", wordVec.front().first.c_str(), wordVec.front().second);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值