PAT甲级A1071---map的常见用法
2020-07-23 本文已影响0人
1nvad3r
1071 Speech Patterns (25分)

分析:
先用transform(str.begin(), str.end(), str.begin(), ::tolower);转为小写,然后遍历截取字符串,统计每个单词出现的次数存在map中。最后遍历map找到出现次数最多的单词。
C++:
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
bool check(char c) {
if (c >= '0' && c <= '9')return true;
if (c >= 'a' && c <= 'z')return true;
return false;
}
int main() {
string str;
getline(cin, str);
transform(str.begin(), str.end(), str.begin(), ::tolower);
map<string, int> mp;
int pos = 0;
while (pos < str.length()) {
string word;
while (pos < str.length() && check(str[pos]) == true) {
word += str[pos];
pos++;
}
if (word != "") {
if (mp.count(word) == 0) {
mp[word] = 1;
} else {
mp[word]++;
}
}
while (pos < str.length() && check(str[pos]) == false) {
pos++;
}
}
string res;
int max = -1;
for (map<string, int>::iterator iter = mp.begin(); iter != mp.end(); iter++) {
if (iter->second > max) {
max = iter->second;
res = iter->first;
}
}
cout << res << " " << max << endl;
return 0;
}