Java O(n)


  • 0
    L
    public String frequencySort(String s) {
        if (s == null || s.isEmpty())
            return s;
    
        int[] occurency = new int[256];
        
        for (int i = 0; i < s.length(); i++)
        {
            occurency[s.charAt(i)]++;
        }
        
        int max = 0;
        int charAtMax = 0;
        StringBuilder builder = new StringBuilder();
        for (int j = 0; j < 256; j++)
        {
            for (int t = j; t < 256; t++)
            {
                if (occurency[t] > max)
                {
                    max = occurency[t];
                    charAtMax = t;
                }
            }
            while (max > 0)
            {
                builder.append((char)charAtMax);
                max--;
            }
            int tmp = occurency[j];
            occurency[j] = max;
            occurency[charAtMax] = tmp;
        }
        
        return builder.toString();
    }

Log in to reply
 

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