Java solution with sorted HashMap


  • 0
    A
        class ValueComparator implements Comparator<Character> {
            Map<Character, Integer> base;
    
            public ValueComparator(Map<Character, Integer> base) {
                this.base = base;
            }
            
            public int compare(Character a, Character b) {
                if (base.get(a) > base.get(b)) {
                    return -1;
                } else {
                    return 1;
                } 
            }
        }
    
        public String frequencySort(String s) {        
            Map<Character, Integer> frequencyMap = new HashMap<>();
            ValueComparator valueComparator = new ValueComparator(frequencyMap);
            Map<Character, Integer> sortedMap = new TreeMap<Character, Integer>(valueComparator);
    
            for(Character ch: s.toCharArray()){
                int value = 0;
                if(frequencyMap.containsKey(ch)){
                    value = frequencyMap.get(ch);
                }
                value++;
                frequencyMap.put(ch, value);
            }
            
            sortedMap.putAll(frequencyMap);
            StringBuffer result = new StringBuffer();
            for(Map.Entry<Character, Integer> each: sortedMap.entrySet()){
                int frequency = each.getValue();
                while(frequency > 0){
                    result.append(each.getKey());
                    frequency--;
                }
            }
            
            return result.toString();
        }
    

Log in to reply
 

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