This is my CPP solution.
class Solution {
public:
string sortString(string s) {
vector<int>freq(26,0);
int n = s.size(), m = 0, dir = 1;
sort(s.begin(),s.end());
if(n==1 && n==2)
return s;
for(int i=0;i<26;i++)
freq[i] = count(s.begin(),s.end(),'a'+i);
for(int i=0;i<n-1;i++){
if(s[i]!=s[i+1])
s[m++]=s[i];
}
s[m++] = s[n-1];
for(int i=0;i<m;i++)
cout << s[i];
cout << endl;
int i = 0;
string ans;
while(n){
if(dir==1){
if(freq[s[i]-'a']>0){
freq[s[i]-'a']--;
ans.push_back(s[i]);
n--;
}
i++;
}
if(i==m){
dir = -1;
i = m-1;
continue;
}
if(dir == -1){
if(freq[s[i]-'a']>0){
freq[s[i]-'a']--;
ans.push_back(s[i]);
n--;
}
i--;
}
if(i==-1){
dir = 1;
i = 0;
continue;
}
}
return ans;
}
};