[PAT解题报告] Speech Patterns

简单题,统计词频,输出出现次数最多的单词,如果不唯一,全部按照字典顺序输出。
注意点: 
(1) 单词定义,数字和字母的连续字符
(2) 字母全转变为小写

可以先把字符串中非数字和字母的位置全变为空白,再用sstream从字符串中一个一个读出连续的字符——这时连续字符只可能是数字和字母了,所以读出一个就是一个单词,利用map统计词频,并记录词频最大值。
遍历map,输出词频等于最大值的所有单词。注意C++ STL map迭代时,自动key的字典顺序由小到大迭代,所以我们不用担心顺序问题。

代码:

#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <cctype>
#include <sstream>

using namespace std;

map<string,int> dic;
char s[1048588];

int main() {
    gets(s);
    for (char *t = s; *t; ++t) {    
        *t = tolower(*t);
        if (!isalnum(*t)) {
            *t = ' ';
        }
    }
    istringstream in(s);
    int f = 0;
    string word;
    while (in >> word) {
        f = max(f, ++dic[word]); 
        
    }
    for (map<string,int>::iterator t = dic.begin(); t != dic.end(); ++t) {
        if (t->second == f) {
            printf("%s %d\n",t->first.c_str(), f);
        }
    }
    return 0;
}

原题链接: http://www.patest.cn/contests/pat-a-practise/1071
全部评论
不是顺序输出呀,输出最小的,pat的解题报告也太不认真了
点赞
送花
回复
分享
发布于 2016-02-25 17:11

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务