[leetcode] 1647. Minimum Deletions to Make Character Frequencies Unique

Description

A string s is called good if there are no two different characters in s that have the same frequency.

Given a string s, return the minimum number of characters you need to delete to make s good.

The frequency of a character in a string is the number of times it appears in the string. For example, in the string “aab”, the frequency of ‘a’ is 2, while the frequency of ‘b’ is 1.

Example 1:

Input: s = "aab"
Output: 0
Explanation: s is already good.

Example 2:

Input: s = "aaabbbcc"
Output: 2
Explanation: You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".

Example 3:

Input: s = "ceabaacb"
Output: 2
Explanation: You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).

Constraints:

  • 1 <= s.length <= 105
  • s contains only lowercase English letters.

分析

题目的意思是:给定一个字符串s,可以删除其中的字符,求能够使字符串字符频率保持唯一最小删除数目。

  • 建立一个字典,统计字符的频率,然后按照频率倒序排序。
  • 然后把相同的频率只保留一个,其他的一个一个删除(并不是完全删,是一个一个删),一个一个删除的时候要用set集合判断一下,不能删除后还有相同频率的字符。删除的时候维护更新res就是答案了哈,即最小删除数。

代码

class Solution:
    def minDeletions(self, s: str) -> int:
        d=defaultdict(int)
        for ch in s:
            d[ch]+=1
        s=set()
        res=0
        d=sorted(d.values(), reverse=True)
        # print(d)
        for v in d:
            while(v in s):
                v-=1
                res+=1
            if(v>0):
                s.add(v)
        return res

参考文献

1647. Minimum Deletions to Make Character Frequencies Unique

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值