题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
首先这道题需要解决两件事情:
- 使用map进行词频统计
- 使用vector对map的pair进行排序
排序又分为2个阶段:
- 词频由大到小排-->直接使用sort按照自定义compare函数排序
- 同频词按照ASCII码由小到大排-->使用双指针,对vector[start,end)段进行自定义compare函数排序
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
bool compare(pair<char, int> pair1, pair<char, int> pair2){
if(pair1.second > pair2.second)
return true;
else
return false;
}
bool compare2(pair<char, int> pair1, pair<char, int> pair2){
if(pair1.first < pair2.first)
return true;
else
return false;
}
int main() {
string s;
getline(cin, s);
int len = size(s);
unordered_map<char, int> hash_map;
vector<pair<char, int> > count;
// 使用map词频统计
for(int i = 0; i < len; i ++){
if(hash_map.find(s[i]) == hash_map.end())
hash_map[s[i]] = 1;
else
hash_map[s[i]]++;
}
// vector存pair
for(auto it = hash_map.begin(); it != hash_map.end(); it++)
count.push_back(*it);
// 先按词频由大到小排序
sort(count.begin(), count.end(), compare);
// 再按ASCII码对同频部分进行由小到大排序
int len2 = size(count);
if(len2 == 1){
cout << count[0].first << endl;
}else{
int ind1 = 0, ind2 = 1;
while(ind2 <= len2){
int val1 = count[ind1].second;
int val2 = count[ind2].second;
if(val1 == val2){
ind2 ++;
}else{
if(ind1 != ind2 - 1)
sort(count.begin()+ind1, count.begin()+ind2, compare2);
ind1 = ind2;
ind2 ++;
}
}
for(int i = 0; i < len2; i ++)
cout << count[i].first;
cout << endl;
}
}
// 64 位输出请用 printf("%lld")

