Permutation of given string that maximizes count of Palindromic substrings
Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.
Note: There can be multiple answers for each string.
Examples:
Input: S = “abcb”
Output: “abbc”
Explanation:
“abbc” is the string with maximum number of palindromic substrings.
Palindromic Substrings are – {“a”, “b”, “b”, “c”, “abbc”}
Input: S = “oolol”
Output: “ololo”
Approach: The idea is to sort the characters of the string such that individually and together form a palindromic substring which will maximize the total palindromic substring possible for the permutation of the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string maxPalindromicSubstring(string s){
sort(s.begin(), s.end());
cout << s;
return s;
}
int main()
{
string s = "abcb" ;
maxPalindromicSubstring(s);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String maxPalindromicSubstring(String s)
{
char tempArray[] = s.toCharArray();
Arrays.sort(tempArray);
System.out.println(tempArray);
return new String(tempArray);
}
public static void main(String[] args)
{
String s = "abcb" ;
maxPalindromicSubstring(s);
}
}
|
Python3
def maxPalindromicSubstring(s):
res = ''.join( sorted (s))
s = str (res)
print (s)
if __name__ = = '__main__' :
s = "abcb"
maxPalindromicSubstring(s)
|
C#
using System;
class GFG{
static String maxPalindromicSubstring(String s)
{
char []tempArray = s.ToCharArray();
Array.Sort(tempArray);
Console.WriteLine(tempArray);
return new String(tempArray);
}
public static void Main()
{
String s = "abcb" ;
maxPalindromicSubstring(s);
}
}
|
Javascript
<script>
function maxPalindromicSubstring(s){
s.sort();
document.write(s.join( "" ))
return s;
}
var s = "abcb" .split( '' );
maxPalindromicSubstring(s);
</script>
|
Time Complexity: O(n*log(n)) where n is the size of the string.
Auxiliary Space: O(1)
Last Updated :
28 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...