Skip to content

409. Longest Palindrome

Hash Table String Greedy

Problem - Longest Palindrome

Easy

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.

 

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

 

Constraints:

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

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def longestPalindrome(self, s: str) -> int:
        count = 0
        odd_appearances = defaultdict(int)

        for char in s:
            odd_appearances[char] ^= 1
            count += 1 if odd_appearances[char] else -1

        return len(s) - count + 1 if count else len(s)

        # length = 0
        # letters = {}
        # max_odd_num = 0

        # for char in s:
        #     letters[char] = letters.get(char, 0) + 1

        # for val in letters.values():
        #     length += ((val // 2) * 2)
        #     if val % 2 == 1:
        #         max_odd_num = max(max_odd_num, val)

        # if max_odd_num != 0:
        #     length += 1
        # return length

Submission Stats:

  • Runtime: 3 ms (39.79%)
  • Memory: 17.6 MB (99.38%)