博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
451. Sort Characters By Frequency - Medium
阅读量:6941 次
发布时间:2019-06-27

本文共 2272 字,大约阅读时间需要 7 分钟。

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.

 

首先用hashmap扫一遍string,统计频率。按频率排序,将hashmap的entry存入max heap,再一个个poll出来,append到StringBuilder

时间:O(NlogN),空间:O(N)

class Solution {    public String frequencySort(String s) {        HashMap
map = new HashMap<>(); PriorityQueue
> maxHeap = new PriorityQueue<>((a, b) -> (b.getValue() - a.getValue())); for(char c : s.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); } for(Map.Entry
entry : map.entrySet()) { maxHeap.offer(entry); } StringBuilder sb = new StringBuilder(); while(!maxHeap.isEmpty()) { Map.Entry
tmp = maxHeap.poll(); for(int j = 0; j < tmp.getValue(); j++) sb.append(tmp.getKey()); } return sb.toString(); }}
class Solution {    public String frequencySort(String s) {        Map
map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); } PriorityQueue
> maxHeap = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); maxHeap.addAll(map.entrySet()); StringBuilder sb = new StringBuilder(); while(!maxHeap.isEmpty()) { Map.Entry
entry = maxHeap.poll(); for(int i = 0; i < entry.getValue(); i++) sb.append(entry.getKey()); } return sb.toString(); }}

 

转载于:https://www.cnblogs.com/fatttcat/p/9988434.html

你可能感兴趣的文章
随记:Linux更改yum源
查看>>
iOS生成二维码
查看>>
DNS基本工作原理,及正反向解析和主从同步测试
查看>>
安装Nginx
查看>>
在树莓派2/B+上安装Python和OpenCV
查看>>
有意思的python***案例
查看>>
PHP Warning 报“timezone”错
查看>>
思科CCIE证书真伪、有效性查询方式
查看>>
局域网内搭建 本地yum 源
查看>>
golang: 常用数据类型底层结构分析
查看>>
How to Set Cores-Per-Socket Parameter for a Virtual Machine
查看>>
我的友情链接
查看>>
如何做出一个弹出窗口
查看>>
solidity 0.5.7简明教程
查看>>
你好啊中国
查看>>
冯柯:同步设计在高性能OLTP数据库中的实践
查看>>
iPhone史上最全的使用教程
查看>>
推广一款不错的应用“锁屏对对碰”
查看>>
Oracle IO问题解析(九)
查看>>
How to Properly Remove Datastore or LUN from ESXi 5.x hosts
查看>>