TreeMap solution Log(N)


  • 1
    public class Solution {
        public String frequencySort(String s) {
            if(s.length() == 0) return "";
            StringBuilder result = new StringBuilder(s.length());
            TreeMap<Integer, LinkedList<Integer>> map = new TreeMap<Integer, LinkedList<Integer>>();
            int [] chart = new int [128];
            for(char temp : s.toCharArray()) {
                int index = temp - 0;
                chart[index]++;
            }
            for(int i = 0; i < chart.length; i++) {
                if(chart[i] != 0) {
                    if(!map.containsKey(chart[i])) {
                        LinkedList<Integer> list = new LinkedList<Integer>();
                        map.put(chart[i], list);
                    }
                    map.get(chart[i]).add(i);
                }
            }
            while(map.size() != 0) {
                int key = map.lastKey();
                LinkedList<Integer> list = map.get(key);
                for(int ch : list)
                   for(int i = 0; i < key; i++)
                       result.append((char)ch);
                map.remove(key);
            }
            return result.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.