451. Sort Characters By Frequency
Posted wentiliangkaihua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了451. 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.
class Solution { public String frequencySort(String s) { if(s == null || s.length() == 0) return ""; int[] arr = new int[256]; for(char c: s.toCharArray()) arr[(int) c]++; Map<Integer, Set<Character>> map = new TreeMap(); for(int i = 0; i < 256; i++){ if(arr[i] != 0){ if(!map.containsKey(arr[i])){ map.put(arr[i], new HashSet()); } map.get(arr[i]).add((char) i); } } List<Integer> list = new ArrayList(map.keySet()); String res = ""; for(int i = 0; i < list.size(); i++){ int t = list.get(i); List<Character> te = new ArrayList(map.get(t)); for(int j = 0; j < te.size(); j++){ for(int k = 0; k < t; k++){ res += te.get(j); } } } StringBuilder output = new StringBuilder(res).reverse(); return output.toString(); } }
1. 用treemap记录频率/charList,然后重构,最后用stringBuilder输出。早上起来脑子不清醒,代码越写越繁琐。
public class Solution { public String frequencySort(String s) { Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1); PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); pq.addAll(map.entrySet()); StringBuilder sb = new StringBuilder(); while (!pq.isEmpty()) { Map.Entry e = pq.poll(); for (int i = 0; i < (int)e.getValue(); i++) sb.append(e.getKey()); } return sb.toString(); } }
2. 用pq按value排序,把map《char, frequency》存入
然后重构
以上是关于451. Sort Characters By Frequency的主要内容,如果未能解决你的问题,请参考以下文章
451. Sort Characters By Frequency
451. Sort Characters By Frequency
451. Sort Characters By Frequency
451. Sort Characters By Frequency