PAT(stl)——1071. Speech Patterns (25)

People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.

Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

Input Specification:

Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return ‘\n’. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].

Output Specification:

For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a “word” is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.

Note that words are case insensitive.

Sample Input:
Can1: “Can a can can a can? It can!”
Sample Output:
can 5

题目大意:

计数题。

题目解析:

可以用string作为map的键值,那就好做了。

具体代码:

#include<iostream>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
map<string,int> m;
int main()
{
	string str,tmp;
	getline(cin,str);
	for(int i=0;i<str.size();i++){
		if(isalnum(str[i])){
			if(isupper(str[i]))
				str[i]=tolower(str[i]);
			tmp+=str[i];
		}
		if(!isalnum(str[i])||i==str.size()-1){
			if(!tmp.empty()){
				m[tmp]++;
				tmp.clear();
			}
		}
	}
	int max=0;
	string maxchar;
	for(auto it=m.begin();it!=m.end();it++){
		if(it->second>max){
			max=it->second;
			maxchar=it->first;
		}
	}
	cout<<maxchar<<" "<<max;
    return 0;
}
全部评论

相关推荐

09-29 17:44
已编辑
蔚来_测(准入职员工)
//鲨鱼辣椒:见不了了我实习了四个月上周再投筛选了一天就给我挂了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
10-12 10:48
已编辑
秋招之苟:邻居家老哥19届双2硕大厂开发offer拿遍了,前几天向他请教秋招,他给我看他当年的简历,0实习实验室项目技术栈跟开发基本不沾边😂,我跟他说这个放在现在中厂简历都过不了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务