LeetCode 409. Longest Palindrome

Post by ailswan Dec. 13, 2023

409. Longest Palindrome

Problem Statement

link: LeetCode.cn LeetCode

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.

Example:

Input: s = "abccccdd" Output: 7

Input: s = "a" Output: 1

Solution Approach

Algorithm

Implement

    class Solution:
    def longestPalindrome(self, s: str) -> int:
      count = collections.Counter(s)
      res = 0
      odd = 0
      for n in count.values():
          if n % 2 == 0:
              res += n
          elif odd == 1:
              res += (n - 1)
          else:
              res += n
              odd = 1
      return res