Find the most common character.
1. use a hashmap.
#include<unordered_map>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream file("a.txt");
string line;
unordered_map<char, int> hashmap;
unordered_map<char, int>::iterator itr;
while(file.good())
{
char c = file.get();
if(c != ' ')
{
if(!hashmap.count(c))
{
hashmap[c] = 1;
}
else
{
int n = hashmap.find(c)->second;
hashmap[c] = ++n;
}
}
}
char result;
int max = 0;
for(itr = hashmap.begin(); itr!=hashmap.end(); itr++)
{
if(itr->second > max)
{
max = itr->second;
result = itr->first;
}
}
cout<<result<<" "<<max<<endl;
system("pause");
return 0;
}
浙公网安备 33010602011771号