【LeetCode】451. Sort Characters By Frequency 解题报告(Python & C++)

时间:2021-07-24 08:28:24

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/sort-characters-by-frequency/description/

题目描述

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.

题目大意

很喜欢这种题目很短,而栗子很多的题目~

题意就是把字符串按照字符出现的次数重新排列。

解题方法

字典

用python真的超级简单呀使用Counter类就能统计每个字符出现的次数,使用most_common函数就能按次序排列,最后字符与其出现的次数相乘就得到了字符串

下面是使用的一个例子的结果:

count = collections.Counter('abbdfas').most_common()
print count # 输出
[('a', 2), ('b', 2), ('s', 1), ('d', 1), ('f', 1)]

代码:

class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
count = collections.Counter(s).most_common()
res = ''
for c, v in count:
res += c * v
return res

优先级队列

C++默认的priority_queue是大顶堆。

C++构造把字符重复多次的新字符串的一个方法是append方法,第一个参数是整形表示重复次数,第二个参数是字符。

C++代码如下:

class Solution {
public:
string frequencySort(string s) {
string res;
unordered_map<char, int> count;
for (char c : s) count[c]++;
priority_queue<pair<int, char>> q;
for (auto a : count) q.push({a.second, a.first});
while (!q.empty()) {
auto t = q.top(); q.pop();
res.append(t.first, t.second);
}
return res;
}
};

排序

参考Grandyang的解法:http://www.cnblogs.com/grandyang/p/6231504.html

我们也可以使用STL自带的sort来做,关键就在于重写comparator,由于需要使用外部变量,记得中括号中放入&,然后我们将频率大的返回,注意一定还要处理频率相等的情况,要不然两个频率相等的字符可能穿插着出现在结果res中,这样是不对的。参见代码如下。

class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> m;
for (char c : s) ++m[c];
sort(s.begin(), s.end(), [&](char& a, char& b){
return m[a] > m[b] || (m[a] == m[b] && a < b);
});
return s;
}
};

日期

2018 年 3 月 4 日
2018 年 12 月 11 日 —— 双十一已经过去一个月了,真快啊。。

【LeetCode】451. Sort Characters By Frequency 解题报告(Python & C++)的更多相关文章

  1. &num;Leetcode&num; 451&period; Sort Characters By Frequency

    https://leetcode.com/problems/sort-characters-by-frequency/ Given a string, sort it in decreasing or ...

  2. LeetCode 451&period; Sort Characters By Frequency (根据字符出现频率排序)

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

  3. &lbrack;LeetCode&rsqb; 451&period; Sort Characters By Frequency 根据字符出现频率排序

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

  4. 【leetcode】451&period;&&num;160&semi;Sort Characters By Frequency

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

  5. 451&period; Sort Characters By Frequency

    题目: Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Inp ...

  6. 451&period; Sort Characters By Frequency将单词中的字母按照从高频到低频的顺序输出

    [抄题]: Given a string, sort it in decreasing order based on the frequency of characters. Example 1: I ...

  7. 451&period; Sort Characters By Frequency &lpar;sort map&rpar;

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

  8. &lbrack;LC&rsqb; 451&period; Sort Characters By Frequency

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

  9. 451&period; Sort Characters By Frequency&lpar;桶排序&rpar;

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

随机推荐

  1. 全球IP分布表

    24.192.0.0 24.195.255.255 亚洲 61.0.0.0 61.255.255.255 亚洲 61.8.0.0 61.8.31.255 澳大利亚 61.128.0.0 61.143. ...

  2. realloc&comma;malloc&comma;calloc函数的区别

    from:http://www.cnblogs.com/BlueTzar/articles/1136549.html realloc,malloc,calloc的区别 三个函数的申明分别是: void ...

  3. 修改PHP 上传文件大小限制

    Windows 环境下的修改方法 ================================================================第一步:修改在php5下POST文件大 ...

  4. 【英语】Bingo口语笔记&lpar;6&rpar; - 表示&OpenCurlyDoubleQuote;迷茫”

  5. &lbrack;置顶&rsqb; 用Wireshark保存RTP的负载码流

    这段时间工作太忙,有些日子没写文章了,今天准备了一篇Wireshark工具的一个小功能,在验证码流的时候非常好用,闲话不说,直接说步骤: 1.打开Wireshark抓取流媒体码流,然后用RTP过滤: ...

  6. JavaScript高级程序设计(学习笔记)

    第13章 事件 一.事件 1.1事件冒泡:事件发生时从里面向外传播   如:div>body>html>document 1.2事件捕获:事件发生时从外层向里层传播   如  doc ...

  7. jquery 实现省市二级联动,附带完整的省市json数据 (粘贴即用)

    1.可以单独定义一个js,保存省市json数据. citydata = { "安徽": [ "合肥", "芜湖", "蚌埠&quo ...

  8. webpack 模块方法

    1. webpack的import和export不需要引入babel 其他ES6语法需要引入babel 2. import引入export导出的模块 3. import()模块分离  低版本浏览器想使 ...

  9. sqlalchemy更新和插入操作

    def save_app_info(self): try: # update app_info print(self.dicts) data = db_session.query(App_Info). ...

  10. 根据银行卡号码获取银行卡归属行以及logo图标

    根据银行卡号码获取银行卡归属地信息接口地址,get请求 https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset= ...