NeetCode #177LC-125EasyTwo PointersBlind 75NC 150NC 250
← Back to All Problems#177 · #125 · Valid Palindrome(验证回文串)
📌 Problem Statement & Constraints
A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forwards and backwards. Given a string
s, return whether it is a palindrome. Constraints: 1 <= s.length <= 2 * 10^5; s consists of printable ASCII characters.💡 Core Algorithmic Approaches
- Use two pointers, one at each end, and move them toward the middle.
- At each step, skip characters that are not alphanumeric on either side.
- Compare the lowercased characters; any mismatch means it is not a palindrome.
- Doing this in place avoids building a filtered copy of the string, so extra space is O(1).
💻 Benchmark Python3 Implementation
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1 # skip non-alphanumeric
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
return True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each pointer traverses the string once.
💾 Space Complexity
O(1) extra: no filtered copy is built, unlike the "".join(filter(str.isalnum, s)) approach which is O(n).
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the inner
i < jguards: the pointers can cross while skipping, causing an out-of-range index. - Using
s[i].isalpha()instead ofisalnum(): digits are also alphanumeric and must be kept. - Building a filtered string and reversing it: correct and short, but O(n) space. The two-pointer version is the expected optimisation.
- Comparing without lowercasing:
'A' != 'a'in ASCII, so case must be normalised.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Two Pointers Problems
中文速览与面试要点
验证回文串
如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样,则可以认为该短语是一个回文串。字母和数字都属于字母数字字符。给你一个字符串 s,如果它是回文串,返回 true;否则返回 false。约束:1 ≤ s.length ≤ 2 × 10^5;s 仅由可打印的 ASCII 字符组成。
核心要点
- 相向双指针(标准解) :左指针 l 从左往右、右指针 r 从右往左,各自跳过非字母数字字符,然后比较 s[l].lower() 与 s[r].lower() 。
- 为什么必须跳过而非预处理 :预处理(过滤 + 转小写)会创建 O(n) 的新字符串;双指针可以原地完成,空间 O(1)。
- 内层 while 也要带 l < r 条件 :否则当字符串全是非字母数字字符时,指针会越界。
- Python 的 str.isalnum() :同时判断字母与数字,比手写 c.isalpha() or c.isdigit() 更简洁。
常见陷阱
- 内层 while 忘记 l < r :当字符串中全无字母数字时(如 "..." ), l 会一直递增到越界,抛 IndexError。
- 只处理大小写不处理非字母数字 :题目要求移除所有非字母数字字符,仅转小写是不够的。
- 用 isalpha() 而非 isalnum() :会漏掉数字,导致 "0P" 这类用例判断错误。
- 用 re.sub 预处理 :正确但引入了正则开销与新字符串。
参考实现
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum(): # 跳过左侧非字母数字
l += 1
while l < r and not s[r].isalnum(): # 跳过右侧非字母数字
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True
# 预处理写法(更短但空间 O(n)):
# t = [c.lower() for c in s if c.isalnum()]
# return t == t[::-1]