NeetCode #15LC-266EasyArrays & HashingNC Algo100
← Back to All Problems#15 · #266 · Palindrome Permutation(回文排列)
📌 Problem Statement & Constraints
Given a string
s, return true if a permutation of s could form a palindrome. Constraints: 1 <= s.length <= 5000; s consists of lowercase English letters.💡 Core Algorithmic Approaches
- A string can be rearranged into a palindrome exactly when at most one character has an odd frequency: the palindrome's mirror pairs consume characters two at a time, leaving at most one unpaired centre character.
- Count the frequencies, then count how many are odd.
- Return whether that count is at most 1.
- Equivalently, use a bitmask and check that at most one bit is set -- a neat O(1)-space variant.
💻 Benchmark Python3 Implementation
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
from collections import Counter
return sum(v % 2 for v in Counter(s).values()) <= 1
# Bitmask variant: parity of each letter tracked as one bit
class Solution2:
def canPermutePalindrome(self, s: str) -> bool:
mask = 0
for ch in s:
mask ^= 1 << (ord(ch) - 97) # XOR toggles the parity bit
return mask & (mask - 1) == 0 # at most one bit set⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass to count, plus a constant-size scan over the 26 letters.
💾 Space Complexity
O(1): the counter holds at most 26 entries, and the bitmask variant uses a single integer.
⚠️ Interview Pitfalls & Follow-ups
- Requiring zero odd counts: an odd-length palindrome always has exactly one odd-count character, so the threshold is
<= 1, not== 0. - Checking whether
sis already a palindrome: the question is about any permutation, not the given order. - Trying to enumerate permutations: factorial time for no reason.
⚡
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,判断 s 的某个排列能否构成一个回文串。约束:1 ≤ s.length ≤ 5000;s 仅由小写英文字母组成。
核心要点
- 回文的充要条件(核心洞察) :一个字符串能重排成回文,当且仅当其中 出现奇数次的字符至多有 1 个 。
- 为什么 :回文是关于中心对称的,除了可能位于正中心的那个字符外,其余每个字符都必须成对出现(左右对称)。
- 实现一 · 计数 :用 Counter 统计,数出现奇数次的字符个数,判断是否 ≤ 1。
- 实现二 · 奇偶切换集合 :遍历字符串,若字符已在集合中则移除(配对成功),否则加入。最终集合大小 ≤ 1 即为回文排列。
常见陷阱
- 以为需要枚举所有排列 :全排列是 O(n!),完全不可行。本题的关键是找到「奇数字符 ≤ 1」这个充要条件。
- 把条件写成「奇数字符 == 1」 :偶长度回文串的奇数字符个数为 0,因此必须是 <= 1 而非 == 1 。
- 忽略单字符与空串 :长度 1 的字符串本身即回文,本解返回 True,正确。
参考实现
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
# 奇偶切换法:集合里剩下的都是「落单」的字符
odd = set()
for ch in s:
if ch in odd:
odd.remove(ch) # 配对成功,抵消
else:
odd.add(ch)
return len(odd) <= 1
# 计数法:
# from collections import Counter
# return sum(v % 2 for v in Counter(s).values()) <= 1