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

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

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

#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
using namespace std;

int main() {
    string s;
    unordered_map<char, int> maps; 
    cin>>s;
    for(auto& x:s){
        maps[x]++;
    }
    int n=s.length();
    auto min_ptr = min_element(maps.begin(), maps.end(),[](auto a,auto b){
        return a.second<b.second;
    });
    unordered_set<char> set;
    for(auto& x:maps){
        if(x.second==min_ptr->second){
            set.insert(x.first);
        }
    }
  //删除模板,O(n)
    int left = 0,right = 0;
    while (left<n&&set.find(s[left])==set.end()) {
        left++;
    }
    right=left+1;
    while (right<n) {
        if(set.find(s[right])==set.end()){
            swap(s[left],s[right]);
            left++;
        }
        right++;
    }
    s.erase(left,n-left);
    cout<<s;

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务