【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".

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

 

posted @ 2022-02-03 09:40  seyjs  阅读(88)  评论(0编辑  收藏  举报