Skip to content

Instantly share code, notes, and snippets.

@ABHIINAV12
Created April 19, 2020 12:23
Show Gist options
  • Save ABHIINAV12/6665f51f989cd6aeb62dff7dc4469803 to your computer and use it in GitHub Desktop.
Save ABHIINAV12/6665f51f989cd6aeb62dff7dc4469803 to your computer and use it in GitHub Desktop.
class Solution {
public:
string reformat(string s) {
int a[50]={0};
int b[56]={0};
for(char c : s){
if(c>='0' && c<='9')
++a[c-'0'];
else ++b[c-'a'];
}
int x=0,y=0;
for(int i=0;i<10;++i) x+=a[i];
for(int i=0;i<26;++i) y+=b[i];
string ret="";
if(abs(x-y)<=1){
if(x<=y){
int tp=0;
int cp=0,cp1=0;
while(x!=0 || y!=0){
if(tp==0)
--y;
else --x;
tp=1-tp;
while(a[cp]==0 && cp<10)
++cp;
while(b[cp1]==0 && cp1<26)
++cp1;
if(tp==1){
ret+='a'+cp1;
b[cp1]--;
}else{
ret+='0'+cp;
a[cp]--;
}
}
}else{
int tp=1;
int cp=0,cp1=0;
while(x!=0 || y!=0){
if(tp==0)
--y;
else --x;
tp=1-tp;
while(a[cp]==0 && cp<10)
++cp;
while(b[cp1]==0 && cp1<26)
++cp1;
if(tp==1){
ret+='a'+cp1;
b[cp1]--;
}else{
ret+='0'+cp;
a[cp]--;
}
}
}
}
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment