Given a string, I need to find the longest palindrome that can be constructed by removing or shuffling characters from the string. If more than one palindrome exists of same length then I need to make ensure that lexicographically smallest one is been given as output. Example : "adskassda" Output expected is : "adsasda"
I am able to find largest palindrome, but how to ensure in case of multiple of same maximum length lexicographically smallest one is been given as output ?
Any palindromic string can be divided into three parts – beg, mid and end. For palindromic string of odd length say 2n + 1, ‘beg’ consists of first n characters of the string, ‘mid’ will consist of only 1 character i.e. (n + 1)th character and ‘end’ will consists of last n characters of the palindromic string. For palindromic string of even length 2n, ‘mid’ will always be empty. It should be noted that ‘end’ will be reverse of ‘beg’ in order for string to be palindrome. I have used same logic for this too.
#include <bits/stdc++.h>
using namespace std;
string longestPalindrome(string str){
map<char,int> frequencyChar;
for(int i=0;i<str.length();i++){
frequencyChar[str[i]]++;
}
char middle_character;
string leftStr;
for(auto it: frequencyChar){
char currentChar=it.first;
int frequencyCurrentChr = it.second;
if(frequencyCurrentChr%2!=0){
middle_character=currentChar;
}
leftStr.append(frequencyCurrentChr/2,currentChar);
}
string rightStr(leftStr.rbegin(),leftStr.rend());
return leftStr + middle_character + rightStr;
}
int main() {
string str = "adskassda";
cout<<longestPalindrome(str);
}
I am getting "adsssda" but expected is "adsasda"