您的位置:首页 > 产品设计 > UI/UE

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

2017-11-10 06:12 639 查看

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.

 

 

 题目标签:Hash Table | Heap

  题目给了我们一个string s, 让我们把s 按照每一个char 的出现频率从大到小排序。

  首先遍历string s,把每一个char 当作 key, 出现次数当作 value 存入 map;

  接着利用priorityQueue,按照 value 从大到小的 顺序 排列,把map 的data 存入 pq;

  遍历 pq,把每一个char 按照 它的value 组成对应长度 string 存入 res。

 

 

Java Solution:

Runtime beats 40.06% 

完成日期:06/23/2017

关键词:HashMap; Priority Queue

关键点:把Map 存入 pq

class Solution
{
public String frequencySort(String s)
{
HashMap<Character, Integer> map = new HashMap<>();
StringBuilder res = new StringBuilder();

// store s char and frequency into map
for(char c: s.toCharArray())
map.put(c, map.getOrDefault(c, 0) + 1);

// set up priorityQueue in value descending order
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
new Comparator<Map.Entry<Character, Integer>>()
{
public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b)
{
return b.getValue() - a.getValue();
}
}
);

// add map into priorityQueue
pq.addAll(map.entrySet());

// iterate pg, add each char with value times into res
while(!pq.isEmpty())
{
Map.Entry<Character, Integer> entry = pq.poll();

for(int i=0; i<(int) entry.getValue(); i++)
res.append(entry.getKey());
}

return res.toString();
}
}

参考资料:

https://discuss.leetcode.com/topic/66024/java-o-n-bucket-sort-solution-o-nlogn-priorityqueue-solution-easy-to-understand

 

LeetCode 题目列表 - LeetCode Questions List

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: