QUESTION:-Given a string with repeated characters, the task is to rearrange characters in a string so that no two adjacent characters are same.
Note : It may be assumed that the string has only lowercase English alphabets.
MY ATTEMPT:-
#include
#include
#include
using namespace std;
void solve(string s){
priority_queue<pair<char,int>> pq;
int cnt[27]={0};
for(int i=0;i<s.length();i++){
cnt[s[i]-‘a’]++;
}
for(int i=0;i<s.length();i++){
pq.push(make_pair(s[i],cnt[s[i]-‘a’]));
}
string res="";
pair<char,int> p;
pair<char,int> prev;
prev.first=’#’;
prev.second=-1;
while(!pq.empty()){
p.first=pq.top().first;
p.second=pq.top().second;
if(p.first==prev.first){
pq.pop();
pair<char,int> temp;
temp.first=pq.top().first;
temp.second=pq.top().second-1;
s+=temp.first;
pq.push§;
if(temp.second>0){
pq.push(temp);
}
prev=temp;
}
else{
s+=p.first;
p.second=pq.top().second-1;
pq.pop();
if(p.second>0)
pq.push(p);
prev=p;
}
}
if(s.length()==res.length()){
cout<<res;
}
else cout<<0;
}
int main(){
//code
solve(“aab”);
return 0;
}
Please point out what i have done wrong by adding comments in the code itself.
Please copy the code to IDE as I cannot post a link here.