PAT 1071 Speech Patterns (25 分)

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




解析

case insensitive.大小写不敏感。
这题要求一句话中出现最多次的单词。题目要求的单词是只包含[0-9][a-z][A-Z]。其他的字母忽略。有的同学可能会这样做:

can1can2!can1can2
先去掉!,变成
can1can2can1can2

但是这样就错了。应该改为can1can2 can1can2



具体实现是:使用map统计每个单词出现次数。最后输出出现次数最多的单词即可

#include<map>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<iostream>
#include<utility>
#include<string>
#include<cctype>
using namespace std;
int main()
{
	string input, process;
	getline(cin, input);
	transform(input.begin(), input.end(), input.begin(), ::tolower);
	for (auto x : input) {
		if (isalnum(x) || x == ' ')
			process += x;
		else
			process += ' ';
	}
	map<string, int> Map;
	size_t i = 0, j;
	do {
		j = process.find_first_of(' ', i);
		Map[process.substr(i, j - i)]++;
		while (j!=string::npos && process[j + 1] == ' ')
			j++;
		i = j + 1;
	} while (j != string::npos);
	auto  data = Map.cbegin();
	for (auto it = Map.cbegin(); it != Map.end(); it++) {
		if (data->second < it->second)
			data = it;
	}
	printf("%s %d\n", data->first.c_str(), data->second);
}

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/84067428