华为机考:HJ102 字符统计

描述

方法1

先将所有字符计算数量,在对比其中字符的assic码

#include#include#include#includeusing namespace std;bool cmp(pair<char, int> a, pair<char, int> b) {if (a.second > b.second) {return true;} else if (a.second == b.second) {return a.first < b.first;} else {return false;}}int main() {string s;while (cin >> s) {vector<pair<char, int>> vec;for (int i = 0; i < s.length(); ++i) {vector<pair<char, int>>::iterator it;for (it = vec.begin(); it != vec.end(); ++it) {if (it->first == s[i]) {it->second++;break;}}if (it == vec.end()) {vec.push_back(make_pair(s[i], 1));}}sort(vec.begin(), vec.end(), cmp);for (int i = 0; i < vec.size(); ++i) {cout << vec[i].first;}cout << endl;}return 0;}

方法2

与方法一一样,不过使用stl比较

#include#include#include#include#include#includeusing namespace std;int main(){string s;map<char, int> mp;while (cin >> s) {mp.clear();for (char c : s) {++mp[c];}vector<pair<char, int>> vec(mp.begin(),mp.end());stable_sort(vec.begin(), vec.end(), [](const pair<char, int>& a, const pair<char, int>& b) {return a.second > b.second;});for (auto iter = vec.begin();iter != vec.end();++iter) {cout << iter->first;}cout << endl;}return 0;}