0
点赞
收藏
分享

微信扫一扫

Leetcode 1647. 字符频次唯一的最小删除次数(可以,终于解决)

文风起武 2022-04-30 阅读 70

在这里插入图片描述

如果字符串 s 中 不存在 两个不同字符 频次 相同的情况,就称 s 是 优质字符串 。

给你一个字符串 s,返回使 s 成为 优质字符串 需要删除的 最小 字符数。

字符串中字符的 频次 是该字符在字符串中的出现次数。例如,在字符串 “aab” 中,‘a’ 的频次是 2,而 ‘b’ 的频次是 1 。

示例 1:

输入:s = “aab”
输出:0
解释:s 已经是优质字符串。
示例 2:

输入:s = “aaabbbcc”
输出:2
解释:可以删除两个 ‘b’ , 得到优质字符串 “aaabcc” 。
另一种方式是删除一个 ‘b’ 和一个 ‘c’ ,得到优质字符串 “aaabbc” 。
示例 3:

输入:s = “ceabaacb”
输出:2
解释:可以删除两个 ‘c’ 得到优质字符串 “eabaab” 。
注意,只需要关注结果字符串中仍然存在的字符。(即,频次为 0 的字符会忽略不计。)

提示:

  • 1 <= s.length <= 10^5
  • s 仅含小写英文字母

主要思路:
先用map存储每个字符出现的次数
将次数存入vector变量
遍历vector,如果元素出现重复,当前每次减一,再次进入循环直至出现次数为1,如果当前元素减到零时,要剔除该元素
code:

class Solution {
public:
    int minDeletions(string s) {
        map<char,int>mymap;
        for(int i=0;i<s.size();i++)
        {
            mymap[s[i]]++;
        }
        
        map<char,int>::iterator it;
        vector<int>white_list;
        for(it=mymap.begin();it!=mymap.end();++it)
        {
            white_list.push_back(it->second);
        }
        sort(white_list.begin(),white_list.end());
        
        int res=0;
        for(int i=0;i<(int)white_list.size();i++)
        {
            int num=white_list[i];
            int cnt=count(white_list.begin(),white_list.end(),num);
            if(cnt>1)
            {
                int temp;
                res++;
                do
                {
                    temp=--white_list[i];
                    if(temp==0)
                    {
                        i=-1;
                        white_list.erase(std::remove(white_list.begin(), white_list.end(), 0), white_list.end());
                        break;
                    }
                    cnt=count(white_list.begin(),white_list.end(),white_list[i]);
                    if(cnt<=1)
                        break;
                    else
                        res++;
                }while(1);
                
            }
        }
        
        
        return res;
        
    }
};
举报

相关推荐

0 条评论