习题5.13-词频统计-编程题

习题5.13-词频统计-编程题

解题代码

#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string, int> words;
int total = 0;
void printk(void) {
	static int flag = 0;
	if (flag) cout << endl;
	else flag = 1;
}
void pushword(string &word,int &cnt) {
	if (words[word] == 0) {
		total++;
		words[word] = 1;
	}
	else {
		words[word]++;
	}
	word = "";
	cnt = 0;
}
int main()
{
	string str, word;
	string m;
	int cnt = 0;
	int max;
	while (cin >> str) {
		for (int i = 0; i < str.length(); i++) {
			if (str[i] == '#') {
				if (cnt > 0) pushword(word, cnt);
				cout << total << endl;
				int final = total / 10;
				for (int i = 0; i < final; i++) {
					max = 0;
					for (auto it : words) {
						if (it.second > max) {
							max = it.second;
							m = it.first;
						}
					}
					printk();
					cout << max << ":" << m;
					words.erase(m);
				}
				return 0;
			}
			if (cnt == 15) {// abc...(15)...abc# abc...(15)...abc,abc
				pushword(word,cnt);
				break;
			}
			if (str[i] >= 'A'&&str[i] <= 'Z') {
				word += (str[i] + 32);
				cnt++;
			}
			else if ((str[i] >= 'a'&&str[i] <= 'z') || (str[i] >= '0'&&str[i] <= '9') || str[i] == '_') {
				word += str[i];
				cnt++;
			}
			else {
				if(cnt>0)
					pushword(word,cnt);
				continue;
			}
			if (i == str.length()-1 && cnt > 0)
				pushword(word, cnt);
		}
	}
	return 0;
}

测试结果

在这里插入图片描述

问题整理

1.题目中:所谓“单词”,是指由不超过80个单词字符组成的连续字符串,但长度超过15的单词将只截取保留前15个单词字符。
意思是:当比较两个单词是否相同时,只比较前15个字符,只要前15个字符相同则相同。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值