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?
输入格式
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
].
输出格式
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
总结
- 这题就看理解了,我开始理解错了题目意思,以为只用算" "内别人说话的内容。实际上这个题需要连前面名字也把单词算进去,比如题目中的Can1也算做一个有效单词
- 在理解对题目意思的基础上这题就好做了,利用
unordered_map<string,int>
来存储每个词出现的次数。直接遍历整个数组,统计有效词出现的次数。 - 在直接在统计次数的时候就进行最大值的比较,让代码看起来更简洁。
AC代码
#include <iostream>
#include<string>
#include<ctype.h>
#include<unordered_map>
using namespace std;
bool isVailed(char c) {
if (isdigit(c) || isalpha(c)) return true;
return false;
}
int main() {
string str, temp, res;
unordered_map<string, int> ans;
int maxn = -1;
getline(cin, str);
for (int i = 0; i < str.size(); i++) {
while (isVailed(str[i]) && i < str.size()) {
temp += tolower(str[i++]);
}
if (temp.size()) { //非空则插入
if (ans.find(temp) != ans.end()) {
ans[temp]++;
}
else {
ans[temp] = 1;
}
if (ans[temp] > maxn) { //更新最大值
maxn = ans[temp];
res = temp;
}
temp.clear();
}
}
cout << res << " " << maxn << endl;
return 0;
}