华为机考: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;
}
相关推荐
小超超爱学习99373 分钟前
大数乘法,超级简单模板
开发语言·c++·算法
Ricardo-Yang17 分钟前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
凌波粒18 分钟前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼27 分钟前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
Utopia^40 分钟前
Flutter 框架跨平台鸿蒙开发 - 起床战争
flutter·华为·harmonyos
autumn200543 分钟前
Flutter 框架跨平台鸿蒙开发 - 习惯养成塔
flutter·华为·harmonyos
李李李勃谦1 小时前
Flutter 框架跨平台鸿蒙开发 - 决策硬币
flutter·华为·harmonyos
sinat_286945191 小时前
harness engineering
人工智能·算法·chatgpt
少许极端1 小时前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
samroom1 小时前
【鸿蒙应用开发 Dev ECO Studio 5.0版本】从0到1!从无到有!最全!计算器------按钮动画、滑动退格、中缀表达式转后缀表达式、UI设计
数据结构·ui·华为·typescript·harmonyos·鸿蒙