#K1461. Longest Palindrome Construction
Longest Palindrome Construction
Longest Palindrome Construction
Given a string s
, determine the maximum length of a palindrome that can be built by rearranging some or all of its characters. In other words, compute the length of the longest palindromic subsequence that can be formed from the characters of s
.
The idea is to use as many characters as possible in pairs and, if any character appears an odd number of times, one extra occurrence can be placed in the center of the palindrome.
You can use the following mathematical formulation: For each character with frequency k, add k if k is even, or add k - 1 if k is odd. If there is at least one odd frequency, add 1 to the final result. In LaTeX, this can be written as:
[ \text{result} = \sum_{\text{for each } k} \begin{cases} k, & \text{if } k \text{ is even}, \ k - 1, & \text{if } k \text{ is odd} \end{cases} ]
If there exists any odd count, then:
[ \text{result} = \text{result} + 1 ]
</p>inputFormat
The input consists of a single line containing a string s
(with only lowercase letters) for which you need to compute the answer.
outputFormat
Output a single integer, which is the maximum possible length of a palindrome that can be constructed by rearranging some or all of the characters of s
.
abccccdd
7