NeetCode #79LC-409EasyArrays & Hashing
← Back to All Problems#79 · #409 · Longest Palindrome(最长回文串)
📌 Problem Statement & Constraints
Given a string
s of lowercase and/or uppercase letters, return the length of the longest palindrome that can be built from its letters. Constraints: 1 <= s.length <= 2000.💡 Core Algorithmic Approaches
- A palindrome is built from pairs of characters, plus optionally one single character in the middle.
- For each character, take the largest even number not exceeding its frequency:
freq // 2 * 2. - If any character has an odd frequency, exactly one leftover character can occupy the centre, adding 1.
- Sum the even parts and add 1 if at least one odd frequency exists.
💻 Benchmark Python3 Implementation
class Solution:
def longestPalindrome(self, s: str) -> int:
from collections import Counter
res = 0
has_odd = False
for c in Counter(s).values():
res += c // 2 * 2 # use as many pairs as possible
if c % 2:
has_odd = True
return res + (1 if has_odd else 0)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n + k): O(n) to count, then a constant-size scan over the distinct characters.
💾 Space Complexity
O(k) for the counter, k <= 52.
⚠️ Interview Pitfalls & Follow-ups
- Adding 1 for every odd frequency: only one character can sit in the centre.
- Returning
len(s): that would require every character to pair up, which fails when an odd count exists. - Ignoring the case distinction between upper and lower case: Python's
Counteris case-sensitive by default, which matches the problem's requirement. - Using
freq // 2instead offreq // 2 * 2: the former counts pairs, not characters.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
最长回文串
给定一个包含大写字母和小写字母的字符串 s,返回通过这些字母构造成的 最长回文串 的长度。在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。约束:1 ≤ s.length ≤ 2000;s 只由小写/大写英文字母组成。
核心要点
- 回文构造规则(核心洞察) :回文中每个字符(除可能位于正中心的那个)都必须成对出现。因此对每个字符,可用其「最大的偶数部分」 v // 2 * 2 个。
- 奇数字符的额外贡献 :若存在任何频次为奇数的字符,可以取其中一个放在正中心,让总长度加 1。
- 为什么最多加 1 :中心位置只能放一个字符,因此无论有多少个奇频字符,最多只能额外贡献 1 个。
- 实现 :累加所有 v // 2 * 2 ,再用一个布尔量记录是否存在奇频字符。
常见陷阱
- 把所有奇频字符都各加 1 :中心位置只能放一个字符,因此最多加 1,不是「有几个奇频就加几」。
- 忘记 v // 2 * 2 的写法 :若写成 v 会直接把所有字符都算进去,导致总长度超过实际可用字符数。
- 误以为必须区分大小写之外还要处理其他字符 :题目限定为英文字母,无需考虑数字或符号。
参考实现
from collections import Counter
class Solution:
def longestPalindrome(self, s: str) -> int:
length = 0
has_odd = False
for v in Counter(s).values():
length += v // 2 * 2 # 只取偶数部分
if v % 2 == 1:
has_odd = True
return length + (1 if has_odd else 0)