其他分享
首页 > 其他分享> > 1071 Speech Patterns

1071 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.

Sample Input:

Can1: "Can a can can a can?  It can!"
 

Sample Output:

can 5

 

题意:

  字频统计,输出出现次数最多的那个单词,注意不区分大小写。

思路:

  用map来统计每个单词的出现次数,如果是大写字母,则将其换为小写。注意:最后一个测试点是卡,字符串的结尾是字母或数字的情况。所以到达最后一个字符的时候,只要temp.length() > 0,都应该将其统计到map中。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 bool cmp(pair<int, string> a, pair<int, string> b) {
 6     if (a.first == b.first)
 7         return a.second < b.second;
 8     else
 9         return a.first > b.first;
10 }
11 
12 int main() {
13     string str;
14     getline(cin, str);
15     string temp;
16     map<string, int> m;
17     for (int i = 0; i < str.length(); ++i) {
18         if (isalnum(str[i])) {
19             temp += (char)tolower(str[i]);
20         } else {
21             if (temp.length() > 0) m[temp]++;
22             temp = "";
23         }
24     }
25     vector<pair<int, string> > v;
26     for (auto it : m) {
27         v.push_back({it.second, it.first});
28     }
29     sort(v.begin(), v.end(), cmp);
30     cout << v[0].second << " " << v[0].first << endl;
31     return 0;
32 }

 

标签:case,word,temp,1071,Patterns,length,Speech,str,first
来源: https://www.cnblogs.com/ruruozhenhao/p/12823356.html