Simple Java two-pass solution using Map and Comparator. O(nlgn)


  • 0
    D

    '''

    public String frequencySort(String s) {
        Character[] chars = new Character[s.length()];
        int[] count = new int[256];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            count[c]++;
            chars[i] = c;
        }
        Arrays.sort(chars, new CharComparator(count));
        StringBuilder sb = new StringBuilder();
        for (char c : chars) {
            sb.append(c);
        }
        return sb.toString();
    }
    
    
    
    class CharComparator implements Comparator<Character> {
        private int[] map;
        public CharComparator(int[] map) {
            this.map = map;
        }
        @Override
        public int compare(Character a, Character b) {
            return map[a] > map[b] ? -1 : (map[a] == map[b] ? (a - b) : 1);
        }
    }
    

    '''


Log in to reply
 

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