#K58692. Longest Palindrome
Longest Palindrome
Longest Palindrome
You are given a multiset of lowercase characters. Your task is to construct the longest palindrome by rearranging the characters. A palindrome is a string that reads the same backward as forward.
For example, given the characters ['a', 'b', 'c', 'b', 'a'], the longest palindrome that can be formed is "abcba". If there are multiple valid answers, printing any one of them is acceptable.
Note: In this problem, you must use the first odd-occurrence character you encounter (in lexicographical order) as the center of the palindrome if any exists.
The palindrome is constructed as follows:
- Count the frequency of each character.
- For each character, add ⌊freq/2⌋ copies to the left half of the palindrome.
- If a character has an odd frequency and you have not chosen a middle character yet, choose that character as the middle of the palindrome.
- Construct the palindrome by concatenating the left half, the middle character (if any), and the reverse of the left half.
The final answer should be printed to stdout.
inputFormat
The input is read from standard input and consists of two parts:
- The first line contains an integer n which denotes the number of characters.
- The second line contains n lowercase characters separated by spaces. When n is 0, the second line will be absent.
outputFormat
Output the longest palindrome that can be formed from the provided characters to standard output.
If the input is empty (i.e. n = 0), output an empty string.
## sample5
a b c b a
abcba