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
结尾无空行

题目大意:统计出现次数最多的单词大小写忽略不计,合法字符是0-9,a-z,A-Z,统一小写输出

显然用map比较好,键是单词,值是出现次数,关键在于如何提取每一个单词

#include <iostream>
#include <map>
#include <string>
using namespace std;
//判断字符是否合法
bool Check(char s)
{
	if (s >= '0' && s <= '9')
		return true;
	if (s >= 'A' && s <= 'Z')
		return true;
	if (s >= 'a' && s <= 'z')
		return true;
	return false;
}
int main()
{
	map<string, int> mp;
	
	string str;
	getline(cin,str);
	//将增量i放到每一步中去
	for (int i = 0; i < str.size();)
	{
		string word;
		int flag = 0;
		while (Check(str[i]))
		{
		//如果是大写,则统一化成小写,方便输出
			if (str[i] >= 'A' && str[i] <= 'Z')
				str[i] += 32;
			word += str[i];
			flag = 1;
			i++;
		}
		if (flag == 1)
		{
			mp[word]++;
			i++;
		}
		else
			i++;
	}
	int max = -1;
	string ans;
	for (map<string, int>::iterator it = mp.begin(); it != mp.end(); it++)
	{
		if (it->second > max)
		{
			max = it->second;
			ans = it->first;
		}
	}
	cout << ans << " " << max;
	return 0;
}
上一篇:PAT 甲级 1013 Battle Over Cities (25 分)(Java)


下一篇:查找树-- 基于后缀字典树实现字符串的模式查找