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<string,int>
来记录每一个单词的出现次数,记住map会自动对插入的单词按照字典序排序,最后输出的时候没必要在特判一下。在对字符串划分单词的时候如果这个字符是字母或者数字就添加到单词中,如果不是就切割并且统计出现次数,同时注意空字符不予以统计(这个地方卡了很久一定要注意)。C++提供了 isalnum()
函数用来判断字符和数字没必要自己在写一个函数。
代码:
#include <bits/stdc++.h>
using namespace std;
map<string, int> dict; //map会自动按照字典序排序
bool check(char ch) {
if (ch >= '0' && ch <= '9') return true;
if (ch >= 'a' && ch <= 'z') return true;
if (ch >= 'A' && ch <= 'Z') return true;
return false;
}
int main() {
string str;
getline(cin, str);
// getchar();
string tmp = "";
for (int i = 0; i < str.size(); i++) {
if (check(str[i])) {
str[i] = tolower(str[i]);
tmp += str[i];
}
if (!check(str[i]) || i == str.length() - 1) {
if (tmp.length() != 0) dict[tmp]++;
tmp = "";
}
}
int ans1 = 0; string ans2 = "";
for (auto ite : dict) {
if (ite.second > ans1) {
ans1 = ite.second;
ans2 = ite.first;
}
}
cout << ans2 << " " << ans1 << endl;
return 0;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章