标签:Deletions tmp 1647 good string Frequencies times frequency dic
题目如下:
A string
s
is called good if there are no two different characters ins
that have the same frequency.Given a string
s
, return the minimum number of characters you need to delete to makes
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'
is2
, while the frequency of'b'
is1
.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
标签:Deletions,tmp,1647,good,string,Frequencies,times,frequency,dic 来源: https://www.cnblogs.com/seyjs/p/15861198.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。