PAT A 1071 Speech Patterns (25分)

一、要点

1、使用map<string, int>统计词的出现次数,然后取最值;
2、注意cctype库中很多使用函数,如:isalnum()为字母数字、isdigit()为数字、isalpha()为字母、isupper()为大写字母、islower()为小写字母、toupper()转为大写字母、tolower()转为小写字母等等。
3、读入单词部分:

    while( ( c = getchar() ) != '\n' )
        if( isalnum(c) )
            str += tolower(c);
        else if( str.size() )//可能有连续多个非字母数字字符
        {
            ++cnt[str];
            str.clear();
        }
    if( str.size() )//统计最后一个单词;
            ++cnt[str];

4、测试点4答案错误:注意是否读入’\n’后还有一个词未统计。

二、代码

#include <cstdio>
#include <map>
#include <string>
#include <cctype>
using namespace std;
int main()
{
	map<string, int> cnt;
	char c;
	string str;
	while( (c = getchar()) != '\n' )
		if( isalnum(c) )
			str += tolower(c);
		else if( str.size() )
		{
			++cnt[str];
			str.clear();
		}
	if( str.size() )
		++cnt[str];
	map<string, int>::iterator ans = cnt.begin();
	for( map<string, int>::iterator it = cnt.begin(); it != cnt.end(); ++it )
		if( it->second > ans->second )
			ans = it;
	printf("%s %d", ans->first.c_str(), ans->second);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值