leetcode-pp / 91alg-11-daily-check

第十一期打卡
3 stars 0 forks source link

【Day 88 】2023-09-05 - 451 根据字符出现频率排序 #90

Open azl397985856 opened 1 year ago

azl397985856 commented 1 year ago

451 根据字符出现频率排序

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/sort-characters-by-frequency/comments/

前置知识

示例 1:

输入: "tree"

输出: "eert"

解释: 'e'出现两次,'r'和't'都只出现一次。 因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。 示例 2:

输入: "cccaaa"

输出: "cccaaa"

解释: 'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。 注意"cacaca"是不正确的,因为相同的字母必须放在一起。 示例 3:

输入: "Aabb"

输出: "bbAa"

解释: 此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。 注意'A'和'a'被认为是两种不同的字符。

freesan44 commented 1 year ago
class Solution {
    func frequencySort(_ s: String) -> String {
        var dict: [Character: Int] = [:]

        for ch in s {
            dict[ch, default: 0] += 1
        }

        let vals = dict.sorted(by: { $0.value > $1.value })

        var res = ""

        for (k, v) in vals {
            res += String(repeating: k, count: v)
        }

        return res
    }
}
Diana21170648 commented 1 year ago

思路

哈希表统计次数 优先队列排序 出堆构成降序字符串

代码

class Solution:
    def frequencySort(self, s: str) -> str:
        dict={}
        for ch in s:
            dict[ch]=dict.get(ch,0)+1
        pq=sorted(dict.items(),key=lambda x:x[1],reverse=True)
        res=[]#存储结果
        for ch,count in pq:
            #count=dict[ch]
            res.append(ch*count)
        return ''.join(res)

复杂度分析

GuitarYs commented 1 year ago
class Solution:
    def frequencySort(self, s: str) -> str:
        # 使用字典存储每个字符出现的次数
        freq_dict = {}
        for c in s:
            freq_dict[c] = freq_dict.get(c, 0) + 1

        # 将字典按值降序排列
        freq_list = sorted(freq_dict.items(), key=lambda item: item[1], reverse=True)

        # 按排序后的顺序拼接结果字符串
        res = ""
        for item in freq_list:
            res += item[0] * item[1]
        return res

# 示例用法
solution = Solution()
s = "tree"
result = solution.frequencySort(s)
print(result)

s = "cccaaa"
result = solution.frequencySort(s)
print(result)

s = "Aabb"
result = solution.frequencySort(s)
print(result)
Alexno1no2 commented 1 year ago
# 最大堆
# 首先遍历字符串,用哈希表记录每个字符出现的次数
# 然后把哈希表中的键值对加到堆中,按照value形成最大堆
# 循环弹出堆中的value最大的字符,将字符根据其出现次数加到res中
class Solution:
    def frequencySort(self, s: str) -> str:
        count = {}
        for c in s:
            count[c] = count.get(c, 0) + 1
        items = [(-val, key) for key, val in count.items()]
        heapq.heapify(items)
        res = ""
        while items:
            val, key = heapq.heappop(items)
            res += key * (-val)
        return res
yetfan commented 1 year ago

代码

class Solution:
    def frequencySort(self, s: str) -> str:
        return ''.join([i[0]*i[1] for i in sorted(Counter(s).items(),key=lambda x:x[1],reverse=True)])