题目传送门:传送门
题意简述
给定有 个单词的字符串,要求替换其中一些字符,使字符串中的字符数量不超过 种,且替换的字符数量最少。
思路
要求替换的字符数量最少,相当于保留的字符数量最多,所以可以开一个桶统计每种字母的出现次数,保留出现次数最多的 种字母,再把其他字母用这 种字母中的其中一个替换掉即可。
code
#include <bits/stdc++.h>
using namespace std;
int n,k,len,tot[30];
string s;
bool vis[30];
struct Node{
char c;
int cnt;
inline bool operator < (const Node &a)const{
return cnt>a.cnt;
}
}buk[30];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
cin.ignore();
getline(cin,s);
for(int i=0;i<s.size();i++){
if(s[i]!=' ') tot[s[i]-'a']++;
}
for(int i=0;i<26;i++){
if(tot[i]) buk[++len].c=i+'a',buk[len].cnt=tot[i];
}
if(len<=k){ //注意如果字符种类本来就小于等于k,那直接输出原字符串就好了
cout<<s;
return 0;
}
sort(buk+1,buk+len+1);
for(int i=1;i<=k;i++) vis[buk[i].c-'a']=true;
for(int i=0;i<s.size();i++){
if(s[i]==' '||vis[s[i]-'a']) cout<<s[i];
else cout<<buk[1].c;
}
return 0;
}