题解 | #字符统计#

字符统计

https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

#include <iostream>
using namespace std;
#include <string>
#include <set>
#include <cctype>
#include <list>

bool mySort(pair<char, int> p1, pair<char, int> p2)
{
	bool res;
	if (p1.second > p2.second)
	{
		res = true;
	}else if(p1.second < p2.second)
	{
		res = false;
	}
	else if (p1.second == p2.second)
	{
		if (p1.first > p2.first)
		{
			res = false;
		}
        else{
            res = true;
        }
	}
	
	return res;
}

int main()
{
	string str;
	getline(cin, str);
	multiset<char> ch;
	for (char i : str)
	{
		ch.insert(i);
	}
	char a = 'a';
	list<pair<char, int>> lst;
	for (int i = 0; i <= 25; i++, a++)
	{
		if (ch.count(a) != 0)
		{
			lst.push_back(pair<char, int>(a, ch.count(a)));
		}
	}

	char b = '0';
	for (int i = 0; i <= 9; i++, b++)
	{
		if (ch.count(b) != 0)
		{
			lst.push_back(pair<char, int>(b, ch.count(b)));
		}
	}
	lst.sort(mySort);
	for (auto p : lst)
	{
		cout << p.first;
	}
}

利用multiset为字符计数,再使用list存储统计后的信息,最后通过自己写的排序函数完成排序后输出

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务