Leetcode451. Sort Characters By Frequency

49 篇文章 0 订阅

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

示例 1:

输入: “tree”

输出: “eert”

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

输入: “cccaaa”

输出: “cccaaa”

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

输入: “Aabb”

输出: “bbAa”

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-characters-by-frequency
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Given a string, sort it in decreasing order based on the frequency of
characters.

Example 1:

Input: “tree”

Output: “eert”

Explanation: ‘e’ appears twice while ‘r’ and ‘t’ both appear once. So
‘e’ must appear before both ‘r’ and ‘t’. Therefore “eetr” is also a
valid answer. Example 2:

Input: “cccaaa”

Output: “cccaaa”

Explanation: Both ‘c’ and ‘a’ appear three times, so “aaaccc” is also
a valid answer. Note that “cacaca” is incorrect, as the same
characters must be together. Example 3:

Input: “Aabb”

Output: “bbAa”

Explanation: “bbaA” is also a valid answer, but “Aabb” is incorrect.
Note that ‘A’ and ‘a’ are treated as two different characters.

C++,简单遍历,20ms,78%

class Solution {
public:
	string frequencySort(string s) {
		unordered_map<char, int> m1;
		for (char i : s) {
			m1[i]++;       //统计<词,频次>
		}
		multimap<int, char> m2;
		for (auto it = m1.begin(); it != m1.end(); ++it) {
			m2.insert({ it->second,it->first });     //反转储存<频次,词>,自动排序
		}
		string s1(s);
		int i = 0;                 //输出
		for (auto it2 = m2.rbegin(); i < s.size()&&it2 != m2.rend(); ++it2) {
			int temp = it2->first;
			while (temp != 0) {
				s1[i]=(it2->second);
				++i;
				--temp;
			}
		}
		return s1;
	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值