#C10802. Longest Palindrome Length
Longest Palindrome Length
Longest Palindrome Length
Given a string s
, find the length of the longest palindrome that can be built with any subset of its characters.
A palindrome is a string that reads the same forwards and backwards. You are allowed to rearrange the characters and choose some or all characters of the string to form the palindrome. The solution should compute the maximum possible length of such a palindrome.
For example, given s = "abccccdd"
, one of the longest palindromes that can be formed is "dccaccd", whose length is 7.
The underlying idea is to count the frequency of each character. For every character with an even frequency, all of them can be used. For characters with an odd frequency, you can use the maximum even count (i.e. frequency - 1) and, if any odd frequency exists, one extra character may be added as the center of the palindrome.
The mathematical formulation can be written as:
\[ \text{result} = \sum_{i} \left( f_i - (f_i \bmod 2) \right) + \begin{cases} 1, & \text{if any } f_i \bmod 2 = 1 \\ 0, & \text{otherwise} \end{cases} \]
inputFormat
The input consists of a single line containing the string s
. The string may include any characters and can be empty.
outputFormat
Output a single integer, which is the length of the longest palindrome that can be built using any subset of characters from s
.
abccccdd
7