Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
azl397985856 opened this issue Sep 4, 2023 · 5 comments
Open

Comments

@azl397985856
Copy link

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
Copy link

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
Copy link

思路

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

代码

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)

复杂度分析

  • 时间复杂度:O(N+KlogK),其中 N 为字符串个数,K为不重复字符串个数。
  • 空间复杂度:O(K),最坏情况下,均不重复,K=N

@GuitarYs
Copy link

GuitarYs commented Sep 5, 2023

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
Copy link

# 最大堆
# 首先遍历字符串,用哈希表记录每个字符出现的次数
# 然后把哈希表中的键值对加到堆中,按照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
Copy link

yetfan commented Sep 5, 2023

代码

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)])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

6 participants