Longest Palindrome
Last updated
Last updated
Given a string of letters, return the length of the longest possible palindrome it can form.
Note: The letters are case sensitive.
We can count the frequency of each letter in a dictionary. Then build the palindrome like an onion from outside to inside by the most frequent letters. The frequency has be even here to surround the inner string. If a letter is used to surround the inner palindrome and is odd, we can use a flag to track the extra reminder value. For example, ababababa
has count 5 and 4. We can use 4 out of 5 a
s to form the onion layer but the extra a
left can also be used in the end as a single middle base.
O(n)
time (create dictionary, iterate through sorted keys)
O(n)
space (dictionary and sorted keys)