337/670

337. Longest Palindrome

Easy

You get a string s of English letters, and case matters: 'A' and 'a' are different characters. Using the letters of s — each one at most as many times as it occurs, arranged in any order you like, with leftovers thrown away — build the longest palindrome you can.

Return the length of that palindrome as an integer; you never have to produce the palindrome itself.

A palindrome reads the same forward and backward, which forces its letters to pair up around the center — at most one letter (the middle of an odd-length palindrome) may appear an odd number of times in what you build.

Example 1:

Input: s = "abccccdd"

Output: 7

Explanation: Pairs available: cc, cc, dd. One 'a' or 'b' can sit in the middle. "dccaccd" uses 3 pairs + 1 center = 7 characters.

Example 2:

Input: s = "a"

Output: 1

Explanation: A single character is already a palindrome of length 1.

Constraints:

  • 1 ≤ s.length ≤ 2000
  • s consists of uppercase and lowercase English letters only

Hints:

Mirror positions in a palindrome hold equal letters, so everything you use must come in pairs — except possibly one letter sitting alone in the exact middle.

Count each character's frequency. A count of c contributes ⌊c/2⌋ pairs (2·⌊c/2⌋ characters). If any count is odd, exactly one leftover character can be promoted to the center: add 1, once, no matter how many odd counts there are.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "abccccdd"

Expected output: 7