leetcode 1647. Minimum Deletions to Make Character Frequencies Unique(所有字母频率不同的最小删除次数)

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”.

每个字母的频率指的是它在字符串s中出现的次数,
要让字符串s中每个字母的频率都不一样,
如果频率一样,要删除字母使它们频率不一样,至少要删几个字母。

思路

一般会想到用hash map记录每个字母出现的次数,然后再想办法删掉频率一样的字母。
因为字母只有26个,所以用一个int数组代表hash map。

如果频率排过序,处理起来会方便很多,只需要从大到小每个频率相差1以上就行,
频率相等的就减频率使它们的频率相差1以上。

注意如果频率都是0,是不需要减频率的,因为都没有这个字母还减什么呢。

public int minDeletions(String s) {
    int[] cnt = new int[26];
    int cur = 0;
    int res = 0;
    
    for(char ch : s.toCharArray()) cnt[ch - 'a'] ++;
        
    Arrays.sort(cnt);
    
    cur = cnt[25];
    for(int i = 24; i >= 0; i --) {
        if(cnt[i] > cur - 1) {
            res += cnt[i] - Math.max(cur - 1, 0);
            cur --;
        } else {
            cur = cnt[i];
        }
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值