华为机考: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;
}
相关推荐
●VON11 小时前
AtomGit Flutter鸿蒙客户端:设置页面
flutter·华为·跨平台·harmonyos·鸿蒙
手写码匠11 小时前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc
无限码力11 小时前
阿里算法岗 0530笔试真题 - 多约束条件下的元素匹配统计
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试
lqqjuly12 小时前
MLA — 多头潜在注意力深度解析
深度学习·神经网络·算法
●VON12 小时前
AtomGit Flutter鸿蒙客户端:用户资料
flutter·华为·架构·跨平台·harmonyos·鸿蒙
吴可可12312 小时前
SolidWorks草图转三维DWG技巧
算法
redaijufeng12 小时前
C++雾中风景7:闭包
c++·算法·风景
风华圆舞12 小时前
Stage 模型下 Flutter 鸿蒙壳工程怎么理解
flutter·华为·harmonyos
小欣加油13 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
祭曦念13 小时前
鸿蒙原生ArkTS布局之RowStart垂直对齐详解
华为·harmonyos