451 Sort Characters By Frequency
生活随笔
收集整理的這篇文章主要介紹了
451 Sort Characters By Frequency
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
451. Sort Characters By Frequency
先統計次數,再按次數構造新的string。思路沒什么難,寫起來還有點麻煩。用了priorityqueue。。
class Wrapper {public char c;public int freq;public Wrapper(char c, int freq) {this.c = c;this.freq = freq;}}public String frequencySort(String s) {if (s==null || s.length() == 0) return "";Map<Character, Integer> map = new HashMap<>();Set<Character> set = new HashSet<>();for (int i = 0; i < s.length(); i++) {int count = map.getOrDefault(s.charAt(i), 0);map.put(s.charAt(i), ++count);set.add(s.charAt(i));}PriorityQueue<Wrapper> pq = new PriorityQueue<>(new Comparator<Wrapper>() {@Overridepublic int compare(Wrapper o1, Wrapper o2) {return o1.freq - o2.freq;}});for (char c : set) {pq.offer(new Wrapper(c, map.get(c)));}StringBuilder sb = new StringBuilder();while (!pq.isEmpty()) {Wrapper w = pq.poll();for (int i = 0; i < w.freq; i++) {sb.insert(0, w.c);}}return sb.toString();} 復制代碼因為用了PriorityQueue所以復雜度是O(nlogn)。 看了別人的答案,有個是O(n)的,用了數組的index表示出現的次數。而且,我上面用了hashset,因為我不太會hashmap的遍歷,下面的代碼也展示了hashmap的遍歷方法, for(char c : map.keySet()):
public String frequencySort(String s) {if (s == null) {return null;}Map<Character, Integer> map = new HashMap();char[] charArray = s.toCharArray();int max = 0;for (Character c : charArray) {if (!map.containsKey(c)) {map.put(c, 0);}map.put(c, map.get(c) + 1);max = Math.max(max, map.get(c));}List<Character>[] array = buildArray(map, max);return buildString(array); }private List<Character>[] buildArray(Map<Character, Integer> map, int maxCount) {List<Character>[] array = new List[maxCount + 1];for (Character c : map.keySet()) {int count = map.get(c);if (array[count] == null) {array[count] = new ArrayList();}array[count].add(c);}return array; }private String buildString(List<Character>[] array) {StringBuilder sb = new StringBuilder();for (int i = array.length - 1; i > 0; i--) {List<Character> list = array[i];if (list != null) {for (Character c : list) {for (int j = 0; j < i; j++) {sb.append(c);}}}}return sb.toString(); } 復制代碼轉載于:https://juejin.im/post/5a31340251882531e944cfab
總結
以上是生活随笔為你收集整理的451 Sort Characters By Frequency的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Swift中的循环强引用 【使用无主引
- 下一篇: 源码阅读中的收获