Simple java solution


  • 0
    R
    class Solution {
        public String frequencySort(String s) {
            //Put the characters and their counts in a map.
            Map<Character, Integer> map = new HashMap<Character, Integer>();
                    for (char c : s.toCharArray()) {
                if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                } else {
                    map.put(c, 1);
                }
            }
    
            StringBuilder str = new StringBuilder();
            int max = 0;
            int val;
            char ch=';';
            
            //Until the map is empty, pick out the character with maximum count
            //from the map and append it to the string. then remove that character from the map.
            
            while(map.size() != 0) {
                max = 0;
               
                for(char c: map.keySet()) {
                    val = map.get(c);
                    if(val>=max)  {max = val; ch = c; } 
                }
                    
                for (int i = 0; i < max; i++) {
                 str.append(ch);
                }      
                map.remove(ch);
            } 
            
            return str.toString();
            
        }
    }
    

Log in to reply
 

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