1071. Speech Patterns (25)解题报告

本文介绍了一个使用C++实现的程序,该程序能够读取输入并统计出现次数最多的字符串及其出现次数。通过使用标准模板库(STL)中的map容器来保存每个字符串及其对应的出现次数,并在遍历过程中实时更新出现次数最多的字符串。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <map>
#include <cctype>
#include <string>
#include <iostream>

using namespace std;
const int N = 1048576;
int main(void) {
    map<string, int> mp;
    map<string, int>::iterator it;
    char *word = new char[N], tmp;
    int i = 0, cnt = -1;
    string str, maxstr;

    do {
        scanf("%c", &tmp);
        if (isalpha(tmp) || isdigit(tmp)) {
            word[i] = tolower(tmp);
            i++;
        }
        else if(i) {
            word[i] = '\0';
            i = 0;
            str = string(word);
            it = mp.find(str);
            if (it == mp.end()) {
                mp[str] = 1;
                if (cnt < 1) {
                    cnt = 1;
                    maxstr = str;
                }
                else if(cnt == 1) {
                    if (str < maxstr) {
                        maxstr = str;
                    }
                }
            }
            else {
                mp[str]++;
                if (mp[str] > cnt) {
                    cnt = mp[str];
                    maxstr = str;
                }
                else if (mp[str] == cnt) {
                    if (str < maxstr) {
                        maxstr = str;
                    }
                }
            }
        }
    } while (tmp != '\n');
    cout << maxstr << ' ' << cnt << endl;
    delete[] word;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值