1071 Speech Patterns (25分)

在这里插入图片描述
注意理解word的定义:仅包含数字和英文字母的为一个单词。其次要注意转换为小写。

#include<string>
#include<cstring>
#include<iostream>
#include<cctype>
#include<unordered_map>
#include<algorithm>
using namespace std;
unordered_map<string, int> record;
int main() {
	string speech;
	getline(cin, speech);
	int i = 0;
	for (int i = 0;i < speech.length();i++) {
		int start = i;
        /*
        Here a "word" is defined as a continuous sequence of alphanumerical characters
         separated by non-alphanumerical characters or the line beginning/end.
        */
		while (start < speech.length() && !isalnum(speech[start])) {	//找到一个单词的开头
			start++;
		}
		if (start >= speech.length()) {
			break;
		}
		int end = start;
		while (end < speech.length() && isalnum(speech[end])) {	//找到一个单词的结尾
			end++;
		}
		string word = speech.substr(start, end - start);
		transform(word.begin(), word.end(), word.begin(), ::tolower);   //string转换大小写
		record[word]++;
		i = end;
	}
	int maxTimes = 0;
	string res = "";
	for (auto it = record.begin();it != record.end();it++) {
		if (it->second > maxTimes || it->second == maxTimes && it->first < res) {
			maxTimes = it->second;
			res = it->first;
		}
	}
	cout << res << " " << maxTimes;
}

二刷:

#include<iostream>
#include<string>
#include<cctype>
#include<unordered_map>
using namespace std;
int main() {
	unordered_map<string, int> book;
	string speech;
	getline(cin, speech);
	int start = 0, end = 0;
	while (start < speech.length()) {
		while (start < speech.length() && !isalnum(speech[start])) {
			++start;
		}
		end = start;
		while (end < speech.length() && isalnum(speech[end])) {
			++end;
		}
		end;
		string word = speech.substr(start, end - start);
		for (int i = 0; i < word.size(); i++) {
			word[i] = tolower(word[i]);
		}
		++book[word];
		start = ++end;
	}
	pair<string, int> res;
	for (auto e : book) {
		if (e.second > res.second) {
			res = e;
		}
	}
	cout << res.first << " " << res.second << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值