Longest Palindrome Problem
Description
LeetCode Problem 409.
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindromethat can be built with those letters.
Letters are case sensitive, for example,"Aa" is not considered a palindrome here.
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
Example 3:
Input: s = "bb"
Output: 2
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase Englishletters only.
Solution
Approach: Count Letters and Use Every Pair
We are free to arrange the letters, so only how many of each letter we have matters. A palindrome reads the same from both ends: every letter on the left half needs a matching copy on the right half. The only exception is the single middle position of an odd-length palindrome, which can hold any one letter.
- Count how often each letter appears (case-sensitive, so
'a'and'A'are different letters). - From a letter that appears
counttimes, we can usecount / 2 * 2copies (the largest even number up tocount): half of them on each side. - If any letter has an odd count, one of its leftover copies can go in the middle: add 1. Add it only once, however many letters have odd counts.
For "abccccdd": c gives 4, d gives 2, and a and b give 0 but leave an odd copy, so the answer is 4 + 2 + 1 = 7 (for example "dccaccd").
The usual mistake is adding 1 for every letter with an odd count, or throwing away all copies of an odd letter instead of using its pairs: a letter that appears 5 times still contributes 4.
Complexity: O(n) time, where n is the length of s, and O(1) space, since there are at most 52 different letters.
import collections
class Solution:
def longestPalindrome(self, s: str) -> int:
length = 0
has_odd = False
for count in collections.Counter(s).values():
length += count // 2 * 2 # use every pair: one letter on each side
if count % 2 == 1:
has_odd = True
# One letter with no partner can sit in the middle.
return length + 1 if has_odd else length
Now write it from memory
Close the write-up and solve it yourself against the tests.