Categories:

Tags:



Problem

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

Constraints

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.

Solution

The problem Longest Palindrome can be solved by counting the number of pairs for each characters and then adding 1 to the result if there is a character that can appear on center.

Implementation

class Solution
{
  public:
    int longestPalindrome(string s)
    {
        unordered_map<char, int> hashmap;
        for (char ch : s)
            hashmap[ch] += 1;

        int even = 0, odd = 0;
        for (auto entry : hashmap)
        {
            even += entry.second >> 1 << 1;
            odd |= entry.second & 1;
        }

        return even + odd;
    }
};