Short Java solution using HashMap and Map.Entry with standard sort


  • 0
    Q
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<>();
    	StringBuilder sb = new StringBuilder();
    
    	// Create hash map for mapping character to occurrence.
            char[] charArray = s.toCharArray();
            for(char c : charArray) {
                if(!map.containsKey(c)) map.put(c, 1);
                else map.put(c, map.get(c)+1);
            }
            
            // Sort entries by their occurrence.
            List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>(){
                public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b){
                return b.getValue().compareTo(a.getValue());
            }
            });
            
            // Build new string based on sorted entries.
            for(Map.Entry<Character, Integer> entry : list){
                for(int i=0; i<entry.getValue(); i++){
            	sb.append(entry.getKey());
                }
            }
            
            return sb.toString();
        }
    }
    

Log in to reply
 

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