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
 1 #include 
 2 #include 
 3 #include 
 4 #include <string>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     string speech;
11     getline(cin, speech);
12 
13     map<string, int> count;
14     int i = 0;
15     string word;
16     while (i < speech.size())
17     {
18         char ch = speech[i];
19         if (isalpha(ch) || isalnum(ch))
20         {
21             if (isupper(ch))
22                 ch = tolower(ch);
23             word.insert(word.end(), ch);
24         }
25         else if (!word.empty())
26         {
27             if (count.find(word) == count.end())
28                 count[word] = 1;
29             else
30                 count[word]++;
31             word.clear();
32         }
33         i++;
34     }
35     if(!word.empty())
36     {
37         if (count.find(word) == count.end())
38             count[word] = 1;
39         else
40             count[word]++;
41     }
42 
43     map<string, int>::iterator it = count.begin();
44     string maxword = it->first;
45     int maxcount = 0;
46     while (it != count.end())
47     {
48         string word = it->first;
49         int cnt = it->second;
50         if (cnt > maxcount||(cnt==maxcount&&word < maxword))
51         {
52             maxcount = cnt;
53             maxword = word;
54         }
55         it++;
56     }
57 
58     cout << maxword << " " << maxcount;
59 }

 

转载于:https://www.cnblogs.com/jackwang822/p/4731002.html

你可能感兴趣的:(PAT 1071. Speech Patterns (25))