with selection sort but very fast because it requires no extra data structures


  • 0
    R
    public class Solution {
        public String frequencySort(String s) {
            if (s.equals("")) return s;
            int size = s.length();
            int[] chars = new int[256];
            for (char c : s.toCharArray()) chars[c]++;
            
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < 256; i++) {
                int maxIndex = 0, freq = 0;
                for (int j = 0; j < 256; j++) {
                    if (chars[j] > freq) {
                        maxIndex = j;
                        freq = chars[j];
                    }
                }
                while (freq-- > 0) result.append((char)maxIndex);
                chars[maxIndex] = 0;
            }
            return result.toString();
        }
    }

Log in to reply
 

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