Java straightforward sort solution using an extra class (Just make it easier to implement the sort).


  • 0
    public String frequencySort(String s) {
        Map<Character, CharFreq> memo = new HashMap<>();
        // Get the frequency of each characters, make it a new obj and push into the map.
        for (int i = 0; i < s.length(); i++) {
            if (!memo.containsKey(s.charAt(i))) {
                CharFreq current = new CharFreq(s.charAt(i));
                memo.put(s.charAt(i), current);
            }
            else {
                CharFreq current = memo.get(s.charAt(i));
                current.freq++;
                memo.put(s.charAt(i), current);
            }
        }
        // Push objects into a list to sort.
        List<CharFreq> list = new ArrayList<>();
        for (Character key: memo.keySet()) {
            list.add(memo.get(key));
        }
       // Sort
        Collections.sort(list, (CharFreq o1, CharFreq o2) -> o2.freq - o1.freq);
       // Recover to string 
        StringBuilder res = new StringBuilder();
        for (CharFreq pair: list) {
            for (int i = 0; i < pair.freq; i++) {
                res.append(pair.c);
            }
        }
        return res.toString();
    }
    class CharFreq {
        char c; 
        int freq;
        public CharFreq(char c) {
            this.c = c;
            this.freq = 1;
        }
    }

Log in to reply
 

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