【Leetcode】451. 根据字符出现频率排序

题目描述:

给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

示例 1:

输入:
"tree"

输出:
"eert"

解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。

示例 2:

输入:
"cccaaa"

输出:
"cccaaa"

解释:
'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。

示例 3:

输入:
"Aabb"

输出:
"bbAa"

解释:
此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
注意'A'和'a'被认为是两种不同的字符。

解题思路:

使用map统计单词出现的次数,然后按照value排序map,最后将map中字符按照个数依次写入string。

AC代码:

class Solution {
public:
static bool comp(pair<char, int> a, pair<char, int> b)
{
	if (a.second >= b.second)
		return true;
	else
		return false;
}
string frequencySort(string s) 
{
	unordered_map<char, int> hash;
	for (int i = 0; i < s.size(); i++)
	{
		if (hash.count(s[i]) == 0) 
			hash[s[i]] = 1;
		else 
			hash[s[i]]++;
	}
	vector<pair<char, int>> count;
	for (unordered_map<char, int>::iterator it = hash.begin(); it != hash.end(); it++)
		count.push_back(pair<char, int>((*it).first, (*it).second));
	sort(count.begin(), count.end(), comp);

	string result;
	for (int i = 0; i < count.size(); i++)
	{
		for (int j = 0; j < count[i].second; j++)
			result += count[i].first;
	}
	return result;
}

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值