Hashmap and Priority Queue Solution


  • 0
    T
    public class Solution {
        class test {
            char mVal;
            int mCount;
            test(char val, int count) {
                mVal = val;
                mCount = count;
            }
            
            public String toString() {
                return "char=" + mVal + " count=" + mCount;
            }
        }
        
        public String frequencySort(String s) {
            if (s == null || s.length() <= 1) {
                return s;
            }    
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            for(int i = 0; i < s.length(); i++) {
                if (map.containsKey(s.charAt(i))) {
                    Integer size = map.get(s.charAt(i));
                    map.put(s.charAt(i), size + 1);
                } else {
                    map.put(s.charAt(i), 1);
                }
            }
            
            PriorityQueue<test> queue = new PriorityQueue<test>(new Comparator<test>() {
                public int compare(test o1, test o2) {
                    return o2.mCount - o1.mCount;
                }
            });
            
            Set<Map.Entry<Character, Integer>> set = map.entrySet();
            for(Map.Entry<Character, Integer> entry : set) {
                queue.add(new test(entry.getKey(), entry.getValue()));
            }
            
    
            StringBuilder builder = new StringBuilder();
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                test obj = queue.poll();
                for(int j = 0; j < obj.mCount; j++) {
                    builder.append(obj.mVal);
                }
            }
            return builder.toString();
        }
    }
    111

Log in to reply
 

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