码迷,mamicode.com
首页 > 其他好文 > 详细

451. Sort Characters By Frequency

时间:2020-05-23 00:36:39      阅读:45      评论:0      收藏:0      [点我收藏+]

标签:tor   amp   res   hashset   together   contains   重构   lan   tput   

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

标签:tor   amp   res   hashset   together   contains   重构   lan   tput   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12940323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!