华为机考: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;
}
相关推荐
小月球~2 小时前
天梯赛 · 并查集
数据结构·算法
仍然.2 小时前
算法题目---模拟
java·javascript·算法
潇冉沐晴4 小时前
DP——背包DP
算法·背包dp
GIOTTO情5 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃5 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾5 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic5 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
csuzhucong5 小时前
puzzle(1037)黑白、黑白棋局
算法
XiYang-DING5 小时前
【LeetCode】链表 + 快慢指针找中间 | 2095. 删除链表的中间节点
算法·leetcode·链表
Zarek枫煜5 小时前
[特殊字符] C3语言:传承C之高效,突破C之局限
c语言·开发语言·c++·单片机·嵌入式硬件·物联网·算法