题解 | #删除字符串中出现次数最少的字符#

删除字符串中出现次数最少的字符

https://www.nowcoder.com/practice/05182d328eb848dda7fdd5e029a56da9

#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
#include <set>
#include <vector>
using namespace std;

int main() {
    string  st;
    int min_num = INT_MAX;
    cin >> st;
    vector<int> lett(26,INT_MAX);
    int n = st.size();
    for(int i=0; i<n; i++){
        if(lett[static_cast<int>(st[i]-'a')] == INT_MAX){
            lett[static_cast<int>(st[i]-'a')] = 1;
        }else{
            lett[static_cast<int>(st[i]-'a')]++;
        }
    }
    for(int i=0; i<26; i++){
        if(min_num > lett[i]){
            min_num = lett[i];
        }
    }
    // cout << min_num << endl;

    set<char> se;
    for(int i=0; i<26; i++){
        if(lett[i] == min_num){
            se.insert(static_cast<char>('a' + i));
        }
    }

    // cout << "se:";
    // for(auto i=se.begin();i!=se.end();i++){
    //     cout << *i;
    // }
    // cout << endl;

    for(int i=0; i<n; i++){
        if(se.find(st[i]) != se.end()){
            st.erase(i, 1);
            // 因为erase函数会直接改变字符串,所以这里要达成 "所有元素依次考虑" , 这里必须对i做出调整
            i--;
        }
    }

    cout << st << endl;
    return 0;
}
// 64 位输出请用 printf("%lld")

整个逻辑分为:

1,统计字符串中各字符出现的个数。

2,找到出现最少的次数。

3,找到对应的字母。

4,删除对应的字母。

全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 11:31
点赞 评论 收藏
分享
我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务