-
Notifications
You must be signed in to change notification settings - Fork 0
【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
Comments
|
思路哈希表统计次数 代码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) 复杂度分析
|
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) |
|
代码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
451 根据字符出现频率排序
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/sort-characters-by-frequency/comments/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: