完美串的定义如下:在一个仅有小写英文字母组成的字符串中,如果其中每一字母出现的次数都相同则成为完美字符串。现在允许你对一个字符串进行若干次删除或者插入操作将其变成一个完美串。每增加一个字母或者删除一个字母都为一次操作,例如对于字符串“abbccc”而言,可以通过增加一个“a”和删除一个"c"将其变成一个完美串,操作次数为2。不难看出,这也是将“abbccc”变成完美串所需的最少操作次数。请编写一个程序计算最少需要进行多少次操作才能实现一个 输入字符串到完美串的转变。
#include<iostream>
#include<queue>
#include<vector>
#include<string>
#include<unordered_map>
#include<algorithm>
using namespace std;
int main(){
string str;
vector<int> show_time;
cin>>str;
unordered_map<char,int>umap;
for(char ch:str){
umap[ch]++;
}
for(auto i:umap){
show_time.push_back(i.second);
}
sort(show_time.begin(),show_time.end());
int MAX=0;
int index=0;
int flag;
for(int j=0; j<show_time.size(); j++){
if(j>0&&show_time[j-1]==show_time[j]) continue;
index=count(show_time.begin()+j,show_time.end(),show_time[j]);
if(MAX<index){
MAX=index;
flag=show_time[j];
}
}
if(MAX==1){
flag=show_time[show_time.size()/2];
}
int cot=0;
for(int k:show_time){
cot+=abs(flag-k);
}
cout<<cot<<endl;
system("pause");
return 0;
}
没有用到动态规划,只是记录自己做题的一个思路。欢迎大家给出建议。