A Way For Learning

Sort based on frequency of characters

No comments
Given a string, sort it in decreasing order based on the frequency of characters.
Input: "tree"
Output:"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.

 So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

import java.util.*;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String output=frequencySort(input);
        System.out.println(output);
    }
    

public static String frequencySort(String s) {
        int[][] count = new int[256][2];
        
        for(char c: s.toCharArray()) {
            count[c][0] = c;
            count[c][1]++;
        }
        
        Arrays.sort(count, new Comparator<int[]>() {
           public int compare(int[] a, int[] b) {
               return a[1] == b[1] ? 0 : (a[1] < b[1] ? 1 : -1);
           } 
        });
        
        
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<256; i++) {
            if (count[i][1] > 0) {
                for(int j=0; j<count[i][1]; j++) {
                    sb.append((char)count[i][0]);
                }
            }
        }
        
        return sb.toString();
    }
}

No comments :

Post a Comment