最后一个测试点过不去,看了这篇:【PAT甲级】1071 Speech Patterns (25分)_SpicyChicken的自我修养-CSDN博客
发现我代码的bug和这里面的一模一样哈哈
while循环结束后,word里可能还存储了一个单词,把它加进去就好了,用if语句判断一下:
if(word.size()!=0)
info[word]++;
完整代码:
#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string, int>info;
map<string, int>result;
int main() {
string s; getline(cin, s);
int index = 0;
string word = "";
while (index < s.size()) {
if (isalnum(s[index]) == 0) {
if (word.size() != 0)
info[word]++;
word = "";
}
else {
if (isupper(s[index])) s[index] = tolower(s[index]);
word += s[index];
}
index++;
}
if(word.size()!=0)
info[word]++;
int max = 0;
for (auto it : info)
if (it.second > max) {
max = it.second;
result.clear();
result[it.first] = it.second;
}
else if (it.second == max) result[it.first] = it.second;
int count = 0;
for(auto it:result){
count++;
cout << it.first << " " << it.second;
if (count != result.size()) cout<<" ";
}
return 0;
}