Java/C#, O(n), simple and easy to understand


  • 2
    A

    C# version:

        public string FrequencySort(string s) 
        {
            if(s == null || s.Length <= 1) return s;
            
            //each element stores the ASCCI and Frequency
            int[][] freq = new int[128][]; 
            for(int i = 0; i < 128; i++)
            {
                freq[i] = new int[2];
                freq[i][0] = i;
            }
            
            foreach(char c in s) freq[c][1]++;
            
            //Sort char by its frequency
            Array.Sort(freq, (x,y) => y[1].CompareTo(x[1])); 
            
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < 128; i++) sb.Append((char)(freq[i][0]), freq[i][1]);
    
            return sb.ToString();
        }
    

    Java verison:

        public String frequencySort(String s) 
        {
            if(s == null || s.length() <= 1) return s;
            
            //each element stores the ASCCI and Frequency
            int[][] freq = new int[128][]; 
            for(int i = 0; i < 128; i++)
            {
                freq[i] = new int[2];
                freq[i][0] = i;
            }
            
            for(Character c: s.toCharArray()) freq[c][1]++;
            
            //Sort char by its frequency
            Arrays.sort(freq, Comparator.comparing((int[] A) -> A[1]).reversed());
            
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < 128; i++)
                for(int j = 0; j < freq[i][1]; j++)
                    sb.append((char)(freq[i][0]));
    
            return sb.toString();
        }
    

Log in to reply
 

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