Python solution with hash

  • 0
    class Solution(object):
        def frequencySort(self, s):
            :type s: str
            :rtype: str
            f = {}
            for c in s:
                f[c] = f.get(c, 0) + 1
            counts = [""] * (len(s) + 1)
            print counts
            for c in f:
                count = f[c]
                counts[count] += c
            res = ""
            for freqLetter in range(len(counts) - 1, -1, -1):
                for c in counts[freqLetter]:
                    res+= (c * freqLetter)
            return res

    The plan is:

    1. Get the count of each letter
    2. Put letters in order based on their count (that's done by putting them in the counts array, the index corresponds to the number of occurrences of the characters at that index)
    3. Build the result by appending index * char for each char in counts, in reverse.

Log in to reply

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