华为机考: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;
}
相关推荐
爱笑的眼睛1135 分钟前
HarmonyOS数据存储Kit深度实践:从架构设计到性能优化
华为·harmonyos
爱笑的眼睛1144 分钟前
HarmonyOS后台代理提醒Agent:构建智能提醒功能的深度解析
华为·harmonyos
爱笑的眼睛111 小时前
ArkTS可选链与空值合并:提升HarmonyOS应用开发的安全性与简洁性
华为·harmonyos
im_AMBER2 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢2 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
寂静山林2 小时前
UVa 1030 Image Is Everything
算法
AI柠檬2 小时前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
星释3 小时前
鸿蒙Flutter三方库适配指南:11.插件发布上线及使用
flutter·华为·harmonyos
weixin_429630263 小时前
第6章 支持向量机
算法·机器学习·支持向量机
SweetCode3 小时前
C++ 实现大数加法
开发语言·c++·算法