Leetcode 451 python 解题报告

AC代码:

class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        dict = {}
        for j in range(len(s)):
            if s[j] in dict:
                dict[s[j]] += 1
            else:
                dict[s[j]] = 1
        list = [[] for i in range(len(s))]
        for key in dict:
            list[dict[key]-1].append(key)
        ans = ""
        for j in range(len(list)-1,-1,-1):
            if list[j] != []:
                for k in list[j]:
                    ans += (j+1)*k
        return ans

思路:统计字符出现次数,然后建立一个索引数组,位置i存储出现i+1次的字符,然后再逆序输出该索引数组中的字符(i+1次)即可。

你可能感兴趣的:(Leetcode)