Reorganize String in C++

C++Server Side ProgrammingProgramming

Suppose we have a string S, check whether the letters can be rearranged so that two characters that are adjacent to each other are not the same. If that is possible, output any possible result. If that is not possible, return the empty string. So if the input is like “AAB”, then the output will be “ABA”.

To solve this, we will follow these steps −

  • Make a priority queue of integer character pairs called pq, define one map m
  • n := size of the string
  • store the character frequency in map m
  • for each key-value pair p in m
    • insert (integer part of p, character part of p)
  • ans := empty string
  • while pq is not empty
    • set one := top pair from pq, and delete the top pair from pq
    • if pq is empty, then
      • if integer part of one > 1, then return empty string
      • ans := ans + character part of one
      • return ans
    • two := top pair from pq, and delete the top pair from pq
    • ans := ans + character part of one
    • ans := ans + character part of two
    • increase integer part of one and two by 1
    • if integer part of one is not 0, then insert one into pq
    • if integer part of two is not 0, then insert one into pq
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string reorganizeString(string S) {
      priority_queue <pair <int, char>> pq;
      map <char, int> m;
      int n = S.size();
      for(int i = 0; i < n; i++){
         m[S[i]]++;
      }
      map <char, int> :: iterator i = m.begin();
      while(i != m.end()){
         pq.push({i->second, i->first});
         i++;
      }
      string ans = "";
      while(!pq.empty()){
         pair <int, char> one = pq.top();
         pq.pop();
         if(pq.empty()){
            if(one.first > 1)
            return "";
            ans += one.second;
            return ans;
         }
         pair <int, char> two = pq.top();
         pq.pop();
         ans += one.second;
         ans += two.second;
         //cout << ans << endl;
         one.first--;
         two.first--;
         if(one.first)pq.push(one);
         if(two.first)pq.push(two);
      }
      return ans;
   }
};
int main() {
   Solution ob1;
   cout << ob1.reorganizeString("AAB") << endl;
   return 0;
}

Input

S = "AAB"
ob1.reorganizeString("AAB")

Output

ABA
raja
Published on 30-Apr-2020 05:56:16

Advertisements