【PAT A1071】Speech Patterns

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.

Hint
注意分割字符串时要考虑末尾的/n,我采取的策略是在字符串后面手动加上一个分隔符

Sample

#include <iostream>
#include <string>
#include <map>
using namespace std;

bool isAlpha(char c){
	return (c >= '0' && c <= '9')||(c >= 'A' && c <= 'Z')||(c >= 'a' && c <= 'z');
}

int main(){
	string input, substr = "";
	getline(cin, input);
	map<string, int> count;
	input += '/';//结束标记
	for(int i = 0; i < input.length(); i++){
		if(isAlpha(input[i])){
			if(input[i] >= 'A' && input[i] <= 'Z')
				input[i] = 'a' + input[i] - 'A';
			substr += input[i];
		}
		else{
			//防止连续出现间隔符
			if(substr != ""){
				if(count.find(substr) != count.end())
					count[substr]++;
				else
					count[substr] = 1;
			}
			substr = "";
		}
	}
	string ans = "";
	int anscnt = 0;
	for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
		//cout << it->first << " " << it->second << endl;
		if(ans == "" || it->second > anscnt || (it->second == anscnt && it->first < ans)){
			ans = it->first;
			anscnt = it->second;
		}
	}
	cout << ans << " " << anscnt << endl;

	return 0;
}
发布了30 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lvmy3/article/details/104125157