注意理解word的定义:仅包含数字和英文字母的为一个单词。其次要注意转换为小写。
#include<string>
#include<cstring>
#include<iostream>
#include<cctype>
#include<unordered_map>
#include<algorithm>
using namespace std;
unordered_map<string, int> record;
int main() {
string speech;
getline(cin, speech);
int i = 0;
for (int i = 0;i < speech.length();i++) {
int start = i;
/*
Here a "word" is defined as a continuous sequence of alphanumerical characters
separated by non-alphanumerical characters or the line beginning/end.
*/
while (start < speech.length() && !isalnum(speech[start])) { //找到一个单词的开头
start++;
}
if (start >= speech.length()) {
break;
}
int end = start;
while (end < speech.length() && isalnum(speech[end])) { //找到一个单词的结尾
end++;
}
string word = speech.substr(start, end - start);
transform(word.begin(), word.end(), word.begin(), ::tolower); //string转换大小写
record[word]++;
i = end;
}
int maxTimes = 0;
string res = "";
for (auto it = record.begin();it != record.end();it++) {
if (it->second > maxTimes || it->second == maxTimes && it->first < res) {
maxTimes = it->second;
res = it->first;
}
}
cout << res << " " << maxTimes;
}
二刷:
#include<iostream>
#include<string>
#include<cctype>
#include<unordered_map>
using namespace std;
int main() {
unordered_map<string, int> book;
string speech;
getline(cin, speech);
int start = 0, end = 0;
while (start < speech.length()) {
while (start < speech.length() && !isalnum(speech[start])) {
++start;
}
end = start;
while (end < speech.length() && isalnum(speech[end])) {
++end;
}
end;
string word = speech.substr(start, end - start);
for (int i = 0; i < word.size(); i++) {
word[i] = tolower(word[i]);
}
++book[word];
start = ++end;
}
pair<string, int> res;
for (auto e : book) {
if (e.second > res.second) {
res = e;
}
}
cout << res.first << " " << res.second << endl;
}