STL_A1071 Speech Patterns (25 分)

https://pintia.cn/problem-sets/994805342720868352/problems/994805398257647616

/*
*string,map的使用
*字符串与出现次数的map映射
*字符串包含大小写单词、数字,注意无效字符
*/
#include<iostream>
using namespace std;
#include<cstdio>
#include<string>
#include<map>

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

int main() {
    string str;
    getline(cin,str); //读入整行字符串
    map<string,int> count;
    map<string,int>::iterator it;
    int i=0; //字符数组下标
    while(i<str.length()) {
        string word;
        while(i<str.length()&&check(str[i])==true) {
            if(str[i] >= 'A' && str[i] <= 'Z') {
                str[i] += 32; //把大写字母转为小写字母
            }
            word += str[i]; //把该字符拼接在单词末尾
            i++;
        }
        if(word != " ") { //统计出现次数
            if(count.find(word) != count.end()) count[word]++;
            else count[word]=1;
        }
        while(i<str.length()&&check(str[i])==false) {
            i++; //跳过无效字符
        }
    }
    string maxWord;
    int maxCount=0;
    for(it=count.begin();it!=count.end();it++) {
        if(it->second > maxCount) {
            maxWord=it->first;
            maxCount=it->second;
        }
    }
    cout<<maxWord<<" "<<maxCount<<endl;
    return 0;
}
posted @ 2019-08-17 15:40  2o2o  阅读(136)  评论(0编辑  收藏  举报