题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805398257647616
第三个测试用例错误。我怀疑我这种算法是无法判断 “beginning/end”这种情况。
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> count;
string change(string a){
for(int i = 0; i < a.length(); i++){
if(a[i] >= 'A' && a[i] <= 'Z'){
char b = a[i] - 'A' + 'a';
a.erase(a.begin() + i);
a.insert(a.begin() + i, b);
}
else if(!(a[i] >= 'a' && a[i] <= 'z') && !(a[i] >= '0' && a[i] <= '9')){
a.erase(a.begin()+i);
i--;
}
}
return a;
}
int main(){
string str;
while(1){
cin>>str;
str = change(str);
if(str.length() > 0){
if(count.find(str) != count.end()){
count[str]++;
}
else
count[str] = 1;
}
if(getchar() == '\n')
break;
}
string word;
int times = -1;
for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
if(times < it->second){
word = it->first;
times = it->second;
}
else if(times == it->second){
if(word > it->first){
word = it->first;
}
}
}
cout<<word<<" "<<times<<endl;
return 0;
}
参考算法笔记的思路,重新写了一种算法:
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> count;
bool judge(char& a){
if(a >= 'a' && a <= 'z')
return true;
else if(a >= 'A' && a <= 'Z'){
a = a - 'A' + 'a';
return true;
}
else if(a >= '0' && a <= '9')
return true;
else
return false;
}
int main(){
string str;
getline(cin, str);
for(int i = 0; i < str.length(); i++){
while(i < str.length() && !judge(str[i]))
i++;
string word;
while(i < str.length() && judge(str[i])){
word += str[i];
i++;
}
if(word.length() > 0){
if(count.find(word) != count.end())
count[word]++;
else
count[word] = 1;
}
}
string word;
int times = -1;
for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
if(times < it->second){
word = it->first;
times = it->second;
}
else if(times == it->second){
if(word > it->first){
word = it->first;
}
}
}
cout<<word<<" "<<times<<endl;
return 0;
}