Simple Java Solution with Count Array


  • 0
    U

    Description - Keeping a count array that stores frequency of all characters along with their ASCII value. Sort the array according to the frequency alone in descending order. Create the string back by traversing the sorted array.

    public static String frequencySort(String s) {
            int[][] count = new int[128][2];
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                count[Integer.valueOf(ch)][0]++;
                count[Integer.valueOf(ch)][1] = Integer.valueOf(ch);
            }
    
            Arrays.sort(count, new Comparator<int[]>() {
                @Override
                public int compare(int[] a, int[] b) {
                    if (a[0] > b[0])
                        return -1;
                    if (a[0] < b[0])
                        return 1;
                    return 0;
                }
            });
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count.length; i++) {
                for (int j = 0; j < count[i][0]; j++) {
                    sb.append((char) count[i][1]);
                }
            }
            return sb.toString();
        }
    

Log in to reply
 

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