Rearrange the string to maximize the number of palindromic substrings in C++

C++Server Side ProgrammingProgramming

We are given with a string ‘str’ of any given length. The task is to rearrange the characters in such a manner that there will be maximum substrings that will be a palindrome string without adding or removing a character from the given input string. Palindrome string is the one in which the characters are arranged in such a manner that they pronounce the same from start and last.

Let us see various input output scenarios for this −

Input − string str = "itnin"

Output − Rearrangement of the string to maximize the number of palindromic substrings is: iinnt.

Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that it will be a maximum palindrome string and if it’s not possible then it will return ‘NOT POSSIBLE’. So the output with the given input string is ‘iinnt.’

Input − string str = "abaaaabb"

Output − Rearrangement of the string to maximize the number of palindromic substrings is: aaaaabbb.

Explanation − We are given a string type variable let’s say, str. Now we will rearrange the characters of an input string in such a manner that it will be a maximum palindrome string and if it’s not possible then it will return ‘NOT POSSIBLE’. So the output with the given input string is aaaaabbb’

Approach used in the below program is as follows

  • Input a variable of string type, let’s say, str and calculate the size of a string and store it in a length named variable.

  • Pass the data to the function Rearr_string(str, length).

  • Inside the function Rearr_string(str, length)

    • Declare an array of integer type of size 26 let’s say, arr[26] and initialise it with 0.

    • Declare a temporary variable ‘temp’ of type string.

    • Start loop FOR from i to 0 till i is less than length. Inside the loop, set arr[str[i] - 'a']++.

    • Start loop FOR from i to 0 till i less than 26. Inside the loop, start another loop FOR from j to 0 till j less than arr[i]. Inside the loop, set temp to temp + (char)(97 + i).

    • Return temp.

  • Print the result.

Example

#include <bits/stdc++.h>
using namespace std;
string Rearr_string(string str, int length){
   int arr[26] = { 0 };
   string temp = "";
   for(int i = 0; i < length; i++){
      arr[str[i] - 'a']++;
   }
   for(int i = 0; i < 26; i++){
      for(int j = 0; j < arr[i]; j++){
         temp = temp + (char)(97 + i);
      }
   }
   return temp;
}
int main(){
   string str = "itinn";
   int length = str.length();
   cout<<"Rearrangement of the string to maximize the number of palindromic substrings is: "<<Rearr_string(str, length);
   return 0;
}

Output

If we run the above code it will generate the following Output

Rearrangement of the string to maximize the number of palindromic substrings is: iinnt
raja
Published on 02-Nov-2021 07:15:32

Advertisements