Easy to understand Java solution using stream()


  • 0
    public class Solution {
        public String frequencySort(String s) {
            
            //Collect the characters with their frequency into a map
            Map<Character, Integer> map = new HashMap<>();
            for(char ch : s.toCharArray()) 
                map.put(ch, map.getOrDefault(ch, 0) + 1);
              
            //Sort the map by value(frequency) 
            StringBuilder sb = new StringBuilder();
            map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .forEach(a -> collect(a,sb));
            
            return sb.toString();
        }
        
        //Store the key(character) and its value(frequency) into the given StringBuilder
        private void collect(Map.Entry<Character, Integer> entry, StringBuilder sb) {
            int count = entry.getValue();
            Character ch = entry.getKey();
            while(count-- > 0) sb.append(ch);
        }
    }
    

Log in to reply
 

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