[LeetCode]1647. Minimum Deletions to Make Character Frequencies Unique (Medium) Python-2023.09.12
Posted on 2023-09-12 17:17 Uriel 閱讀(56) 評論(0) 編輯 收藏 引用 所屬分類: 貪心 、閑來無事重切Leet Code 、Hash給出一堆字符,問最少去掉幾個字符可以保證每種字符出現(xiàn)的次數(shù)不同,用python的counter統(tǒng)計次數(shù),然后用set記錄已經(jīng)出現(xiàn)過的字符頻次,若有沖突,不斷去掉字符直至不沖突
1 #1647
2 #Runtime: 274 ms (Beats 29.54%)
3 #Memory: 14.2 MB (Beats 87.50%)
4
5 class Solution(object):
6 def minDeletions(self, s):
7 """
8 :type s: str
9 :rtype: int
10 """
11 ans = 0
12 fq_set = set()
13 cnt = collections.Counter(s)
14 for ch, fq in cnt.items():
15 while fq and fq in fq_set:
16 fq -= 1
17 ans += 1
18 fq_set.add(fq)
19 return ans
2 #Runtime: 274 ms (Beats 29.54%)
3 #Memory: 14.2 MB (Beats 87.50%)
4
5 class Solution(object):
6 def minDeletions(self, s):
7 """
8 :type s: str
9 :rtype: int
10 """
11 ans = 0
12 fq_set = set()
13 cnt = collections.Counter(s)
14 for ch, fq in cnt.items():
15 while fq and fq in fq_set:
16 fq -= 1
17 ans += 1
18 fq_set.add(fq)
19 return ans