# map本身有序，存入小写英文单词，希望从小到大再从大到小输出，有误

0
[已解决问题] 解决于 2020-03-09 22:06

eg:
"aaaabbbbbcccc"

a=4
b=5
c=4

a b c

c b a

https://leetcode.com/contest/biweekly-contest-21/problems/increasing-decreasing-string/

class Solution {
public:
string sortString(string s) {
if(s.empty()) return "";
map<char,int> mp;
for(int i=0;i<s.size();++i)
mp[s[i]]++;
for(auto &it:mp)
{
cout<<it.first<<" "<<it.second<<endl;
}
string ans="";
while(!mp.empty())
{
for(auto &it:mp)
{
ans+=it.first;
it.second--;
if(it.second==0) mp.erase(it.first);
}
for(auto &it:mp)
{
cout<<it.first<<" "<<it.second<<endl;
}
for(map<char,int>::reverse_iterator it=mp.rbegin();it!=mp.rend();++it)
{
cout<<"**"<<(*it).first<<endl;
ans+=it->first;
it->second--;
if(it->second==0) mp.erase(it->first);
}
cout<<ans<<endl;
for(auto &it:mp)
{
cout<<it.first<<" "<<it.second<<endl;
}
}
return ans;
}
};

1

mp.erase(it->first)

``````            for(auto &it:mp)//这是构造升序字符串
{
ans+=it.first;
it.second--;
if(it.second==0) mp.erase(it.first);
}
for(auto &it:mp)
{
cout<<it.first<<" "<<it.second<<endl;
}
for(map<char,int>::reverse_iterator it=mp.rbegin();it!=mp.rend();++it)//这是构造降序字符串，但是这次这个循环一定会执行吗，考虑这种字符串：aaabbbccc ，
{
cout<<"**"<<(*it).first<<endl;
ans+=it->first;
it->second--;
if(it->second==0) mp.erase(it->first);
}
cout<<ans<<endl;
for(auto &it:mp)
{
cout<<it.first<<" "<<it.second<<endl;
}``````

``````class Solution {
public:
string sortString(string s) {
map<char, int> table;
for(auto c : s){
table[c] = table[c] + 1;
}
string res;
bool up = 1;
while(table.size() != 0){
bool finish = true; //为了加速退出
if(up){
map<char, int>::iterator begin = table.begin();
map<char, int>::iterator end = table.end();
up = 0;
for(; begin != end; begin++){
if(begin->second == 0){
continue;
}
finish = false;
res += begin->first;
begin->second = begin->second - 1;
}
}else{
map<char, int>::reverse_iterator begin = table.rbegin();
map<char, int>::reverse_iterator end = table.rend();
up = 1;
for(; begin != end; begin++){
if(begin->second == 0){
continue;
}
finish = false;
res += begin->first;
begin->second = begin->second - 1;
}
}
if(finish)
break;
}
return res;
}
};``````

PS：如果提问后，有人回答了满意的答案，请及时给予采纳，这样这个社区才会越来越好，有问题随时沟通，谢谢

wengle | 小虾三级 |园豆：567 | 2020-03-08 16:57

您需要登录以后才能回答，未注册用户请先注册