华为机考:HJ102 字符统计

华为机考:HJ102 字符统计

描述

方法1

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

cpp 复制代码
#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;
}

方法2

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

cpp 复制代码
#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;
}
相关推荐
专注前端30年30 分钟前
智能物流路径规划系统:核心算法实战详解
算法
json{shen:"jing"}1 小时前
字符串中的第一个唯一字符
算法·leetcode·职场和发展
追随者永远是胜利者1 小时前
(LeetCode-Hot100)15. 三数之和
java·算法·leetcode·职场和发展·go
BlockWay2 小时前
西甲赛程搬进平台:WEEX以竞猜开启区域合作落地
大数据·人工智能·算法·安全
im_AMBER4 小时前
Leetcode 121 翻转二叉树 | 二叉树中的最大路径和
数据结构·学习·算法·leetcode
lqj_本人4 小时前
Flutter三方库适配OpenHarmony【apple_product_name】华为Pura系列设备映射表
flutter·华为
mit6.8244 小时前
二分+贪心
算法
programhelp_5 小时前
特斯拉 MLE 超详细面经 + 避坑
数据结构·人工智能·算法·面试·职场和发展
木斯佳5 小时前
HarmonyOS实战(解决方案篇)—深色模式适配完全指南:从原理到实践
华为·harmonyos
越甲八千5 小时前
深入了解迭代器erase()之后的失效逻辑
算法