曾经沧海难为水,除却巫山不是云。|

Joey-Wang

园龄:4年3个月粉丝:17关注:0

6.4 map的常见用法详解

6.4 map的常见用法详解

http://codeup.hustoj.com/contest.php?cid=100000599

A Speech Patterns (25)

image-20200801172139893

题目释义

给定字符串,输出其中出现频率最高的单词及出现次数。【忽略字符大小写,输出一律大写】

若有频率一样高的单词,则根据字典序输出最小的那个单词。

⚠️单词包括字母和数字,遇到非字母和数字或行尾时即代表单词的结束。

题目解析

要读入一行,可使用gets然后赋值给string,或直接getline(cin, s);

用map建立string到int的映射,因为map键不重复且自动从小到大排序,故无需在意频率相同时输出的问题。

代码

#include <cstdio>
#include <iostream>
#include <string>
#include <map>

using namespace std;

bool alphanumerical(char &a) {
    if (a >= 'A' && a <= 'Z') {
        a += 32;
        return true;
    }
    if (a >= 'a' && a <= 'z') return true;
    if (a >= '0' && a <= '9') return true;
    return false;
}

int main() {
    char str[1048600];
    string s, subs;
    while (gets(str)) {  //或getline(cin,s);
        s = str;
        map<string, int> mp;
        for (int i = 0; i < s.length(); i++) {
            bool temp = alphanumerical(s[i]);
            if (temp) subs += s[i];
            if (!temp || i == s.length() - 1) {
                if (subs.length() != 0) mp[subs]++;
                subs.clear();
            }
        }
        string ans;
        int temp = 0;
        for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++) {
            if (it->second > temp) {
                ans = it->first;
                temp = it->second;
            }
        }
        printf("%s %d\n", ans.c_str(), temp);
    }
    return 0;
}

本文作者:Joey-Wang

本文链接:https://www.cnblogs.com/joey-wang/p/14541174.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Joey-Wang  阅读(65)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开