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
思路:使用map保存字符串出现的个数

注意:不要使用scanf和cin来读取字符串,只能通过一个个的读取字符。比如:输入了asd*^&123,如果用scanf("%s",s)会有问题



#include <iostream>
using namespace std;
#include<string>
#include<map>
#include<algorithm>
#include<vector>
typedef struct node{
	int num;
	string s;
}Node;
bool compareNode(Node n1, Node n2){
	if(n1.num>n2.num||(n1.num==n2.num)&&n1.s.compare(n2.s)<0){
		return true;
	}
	return false;
}
int main()
{
	char c;
	string s="";
	map<string,int> m;
	c=getchar();
	while(c!='\n'){
		if(c>='0'&&c<='9'||c>='a'&&c<='z')
		    s+=c;
        else if(c>='A'&&c<='Z'){
        	s+=(c-'A'+'a');
        }    
	    else{
	    	if(s.compare("")!=0)
    			m[s]++;
	    	s="";
	    }
        c= getchar();
	}
	m[s]++;//缺少该句,会报段错误,考虑这样的输入:*******S 
	vector<Node> r;
	map<string, int> ::iterator iter;
	for(iter=m.begin();iter!=m.end();iter++){
		Node n;
		n.s = iter->first;
		n.num = iter->second;
		r.push_back(n);
	} 
	sort(r.begin(),r.end(),compareNode);
	cout<<r[0].s<<" "<<r[0].num<<endl;
	return 0;
}



posted @ 2014-03-14 10:40  bingtel  阅读(174)  评论(0编辑  收藏  举报