leetcode1647. Minimum Deletions to Make Character Frequencies Unique

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1647. 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".

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.

解题思路:先统计出每个字符出现的次数,然后从最大的出现次数开始,若不唯一,则将次数减一,再判断是否重复,循环直到不重复为止。

代码如下:

class Solution(object):
    def minDeletions(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        dic = 
        for i in s:
            dic[i] = dic.setdefault(i,0)+1

        times = sorted(dic.itervalues())

        for val in dic.itervalues():
            if times.count(val) <= 1:continue
            tmp = val
            while tmp >= 0:
                if tmp not in times:break
                tmp -= 1
            times.pop(times.index(val))
            if tmp != 0: times.append(tmp)
            res += (val - tmp)
        return res

 

以上是关于leetcode1647. Minimum Deletions to Make Character Frequencies Unique的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Minimum Height Trees

leetcode:Minimum Subarray

leetcode@ [310] Minimum Height Trees

LeetCode -- Minimum Path Sum

LeetCode 2187. Minimum Time to Complete Trips

[LeetCode]Minimum Path Sum