solution1
分别统计字符String
的个数,并按照该顺序输出
#include<iostream>
#include<string>
#include<map>
using namespace std;
map<char, int> mp;
void handle(char c){
if(mp.count(c)){
cout << c;
mp[c]--;
if(mp[c] == 0) mp.erase(c);
}
}
int main(){
string s, m = "String";
cin >> s;
for(int i = 0; i < s.size(); i++){
if(s[i] == 'S' || s[i] == 't' || s[i] == 'r' || s[i] == 'i' || s[i] == 'n' ||s[i] == 'g'){
if(mp.count(s[i])) mp[s[i]]++;
else mp[s[i]] = 1;
}
}
while(mp.size()){
for(int i = 0; i < m.size(); i++){
handle(m[i]);
}
}
return 0;
}
solution2
#include<iostream>
#include<string>
using namespace std;
int main(){
string s, m = "String";
int flag[150] = {0}, ans = 1;
cin >> s;
for(int i = 0; i < s.size(); i++){
flag[s[i]]++;
}
while(ans){//上一轮有输出,则还有必要尝试下一轮
ans = 0;//默认本轮没有输出,则已经全部输出无需继续
for(int i = 0; i < m.size(); i++){
if(flag[m[i]] > 0){
cout << m[i];
flag[m[i]]--;
ans = 1;
}
}
}
return 0;
}