Given a string S consisting of lowercase characters(a-z) only, the task is to print a new string by rearranging the string in such a way that maximizes the number of palindromic substrings. In case of multiple answers, print any one.
Note: even if some substrings coincide, count them as many times as they appear in the obtained string.
Examples:
Input: s = “aabab”
Output: ababa
string “ababa” has 9 palindromic substrings: “a”, “b”, “a”, “b”, “a”, “aba”, “bab”, “aba”, “ababa”.
Input: s = “aa”
Output: aa
The given string has the maximum number of palindromic substrings possible, “a”, “a” and “aa”.
The problem might look to be a complex one but on solving for various cases and having observations will lead to an easy solution.
A simple solution is to sort the string and print it. Sorting takes O(N * log N). An efficient solution is to count the frequency of each character using a freq[] array and then construct the string using the freq[] array.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
string newString(string s)
{
int l = s.length();
int freq[26] = { 0 };
for ( int i = 0; i < l; i++) {
freq[s[i] - 'a' ] += 1;
}
string ans = "" ;
for ( int i = 0; i < 26; i++) {
for ( int j = 0; j < freq[i]; j++) {
ans += ( char )(97 + i);
}
}
return ans;
}
int main()
{
string s = "aabab" ;
cout << newString(s);
return 0;
}
|
Java
public class GFG {
static String newString(String s)
{
int l = s.length();
int freq[] = new int [ 26 ] ;
for ( int i = 0 ; i < l; i++) {
freq[s.charAt(i) - 'a' ] += 1 ;
}
String ans = "" ;
for ( int i = 0 ; i < 26 ; i++) {
for ( int j = 0 ; j < freq[i]; j++) {
ans += ( char )( 97 + i);
}
}
return ans;
}
public static void main(String args[])
{
String s = "aabab" ;
System.out.println(newString(s));
}
}
|
Python3
def newString(s):
l = len (s)
freq = [ 0 ] * ( 26 )
for i in range ( 0 , l):
freq[ ord (s[i]) - ord ( 'a' )] + = 1
ans = ""
for i in range ( 0 , 26 ):
for j in range ( 0 , freq[i]):
ans + = chr ( 97 + i)
return ans
if __name__ = = "__main__" :
s = "aabab"
print (newString(s))
|
C#
using System;
class GFG
{
static String newString( string s)
{
int l = s.Length;
int [] freq = new int [26];
for ( int i = 0; i < l; i++)
{
freq[s[i] - 'a' ] += 1;
}
string ans = "" ;
for ( int i = 0; i < 26; i++)
{
for ( int j = 0; j < freq[i]; j++)
{
ans += ( char )(97 + i);
}
}
return ans;
}
public static void Main()
{
string s = "aabab" ;
Console.Write(newString(s));
}
}
|
Javascript
<script>
function newString(s)
{
let l = s.length;
let freq = new Array(26);
freq.fill(0);
for (let i = 0; i < l; i++)
{
freq[s[i].charCodeAt(0) - 'a' .charCodeAt(0)] += 1;
}
let ans = "" ;
for (let i = 0; i < 26; i++)
{
for (let j = 0; j < freq[i]; j++)
{
ans += String.fromCharCode(97 + i);
}
}
return ans;
}
let s = "aabab" ;
document.write(newString(s));
</script>
|
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(26)