-
Vector/Map-OpenJudge-统计字符数
-
题目链接:
6:统计字符数
-
思路:
在统计单词,字符方面,map有得天独厚的优势,不过有点烦,map的排序是按照key值排的,又没有自定义排序,所以只能用vector把map中所有的pair搬过来排序
-
代码:
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<string>
using namespace std;
typedef pair<char, int> p;
bool cmp(p a, p b)
{
if (a.second < b.second)
return true;
else if (a.second > b.second)
return false;
else
return a.first > b.first;
}
int t;
int main()
{
cin >> t;
while (t--)
{
map<char, int> Words_map;
vector<p> Words_vec;
string str;
int i = 0;
cin >> str;
if (str.empty()) //空行忽略
{
t++;
continue;
}
while (i!=str.length())
{
auto it_end = Words_map.end();
auto it = Words_map.find(str[i]);
if (it != it_end)
it->second++;
else
Words_map.insert(p(str[i], 1));
i++;
}
for (auto it = Words_map.begin(); it != Words_map.end(); it++)
Words_vec.push_back(p(it->first, it->second));
sort(Words_vec.begin(), Words_vec.end(), cmp);
auto it = Words_vec.end();
it--;
cout << it->first << " " << it->second << endl;
}
return 0;
}