Problem Description
Given a string s consisting of lowercase or uppercase English letters, determine the length of the longest palindrome that can be built with those letters. Letters are case sensitive.
Key Insights
- Count the frequency of each character.
- For each character, you can use pairs (even count or odd count minus one) to form the palindrome.
- If any character has an odd frequency, you can add one extra character as the center of the palindrome.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) since the frequency counter will have at most 52 keys (considering both uppercase and lowercase letters).
Solution
The solution uses a hash table to count the frequency of each character. For every character, the maximum number of characters that can be used in a palindrome is determined by taking the largest even number that is less than or equal to its frequency (which is frequency - (frequency % 2)). If there exists any character with an odd frequency, one of these can be used as the center of the palindrome, adding an extra character to the total length. This greedy approach efficiently computes the length of the largest possible palindrome from the available characters.