Loading...

09-12 leetcode-1647

链接 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.

题解

这题哈希表统计次数,然后贪心删除即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from collections import Counter


class Solution:
def minDeletions(self, s: str) -> int:
counter = Counter(s)
index = {}
for key, value in counter.items():
index.setdefault(value, []).append(key)
result = 0
need_delete = sorted(filter(lambda x: len(index[x]) > 1, index.keys()), reverse=True)
for i in need_delete:
for _ in range(len(index[i]) - 1):
for j in range(i, -1, -1):
if j not in index:
result += i - j
if j != 0:
index[j] = ["-1"]
break
return result

Comment