Java in HashMap & Bucket Sort, similar to Top K problem


  • 0

    Actually, this problem can be solved by only use bucket things, but if we can solve multiple problems in one certain method, isn't that a great idea?

        public String frequencySort(String s) {
            if (s == null || s.length() == 0) {return "";}
            char[] t = s.toCharArray();
            HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
            LinkedList<Character>[] bucket = new LinkedList[s.length() + 1];
            StringBuilder sb = new StringBuilder();
            
            for (char c: t) {hash.put(c, hash.getOrDefault(c, 0) + 1);}
            
            for (char c: hash.keySet()) {
                int num = hash.get(c);
                if (bucket[num] == null) {bucket[num] = new LinkedList();}
                bucket[num].offer(c);
            }
            
            for (int i = s.length(); i >= 0 && sb.length() < s.length(); i--) {
                if (bucket[i] == null) {continue;}
                while (!bucket[i].isEmpty()) {
                    char c = bucket[i].poll();
                    for (int j = 0; j < i; j++) {
                        sb.append(c);
                    }
                }
            }
            
            return sb.toString();
        }
    

Log in to reply
 

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