我是靠谱客的博主 明亮柜子,这篇文章主要介绍LeetCode——451. 根据字符出现频率排序题目思路代码结果,现在分享给大家,希望可以做个参考。

根据字符出现频率排序

  • 题目
  • 思路
  • 代码
  • 结果

题目

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

思路

一开始,误以为只有字母,结果wa了。后来想了一下,改用hashmap来统计字符的个数,再将map中的键值对遍历到优先队列中,利用优先队列构造字符串直到队列为空!

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Queue; class Element { char temp; int num; public Element(char temp,int num) { this.temp=temp; this.num=num; } } class Solution { public String frequencySort(String s) { int length=s.length(); HashMap<Character,Integer> map=new HashMap<>(); char temp; // 统计字符数目 for (int i = 0; i < length; ++i) { temp=s.charAt(i); if (map.containsKey(temp)) { map.put(temp,map.get(temp)+1); } else map.put(temp,1); } Comparator<Element>comparator=new Comparator<Element>() { @Override public int compare(Element o1, Element o2) { return o2.num- o1.num; } }; Queue<Element>queue=new PriorityQueue<>(comparator); map.forEach((k,v)->{ queue.add(new Element(k,v)); }); StringBuilder ans=new StringBuilder(); while (!queue.isEmpty()) { Element a=queue.poll(); while (a.num!=0) { ans.append(a.temp); --a.num; } } return ans.toString(); } }

结果

没什么技术含量,就是利用了一些容器的特性而已!
在这里插入图片描述

最后

以上就是明亮柜子最近收集整理的关于LeetCode——451. 根据字符出现频率排序题目思路代码结果的全部内容,更多相关LeetCode——451.内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部