赞
踩
先将所有字符计算数量,在对比其中字符的assic码
#include<iostream> #include<vector> #include<algorithm> #include<string> using 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; }
与方法一一样,不过使用stl比较
#include<iostream> #include<map> #include<string> #include<vector> #include<iterator> #include<algorithm> using 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; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。