实现说明
双指针回文判定以函数 is_palindrome为骨架。
while left < right 承担全部的逐项处理。
使用要点
- 跑完文件,输出里会留下标记——
half comparisons for racecar:。 is_palindrome是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 文件在加载时定义 is_palindrome。
签名一览:def is_palindrome(text)
核心语句
elif text[left].lower() != text[right].lower():
return False
elif not text[right].isalnum():
right -= 1
代码示例
def is_palindrome(text):
"""Palindrome check with two pointers comparing mirrored ends."""
left, right = 0, len(text) - 1
while left < right:
if not text[left].isalnum():
left += 1
elif not text[right].isalnum():
right -= 1
elif text[left].lower() != text[right].lower():
return False
else:
left += 1
right -= 1
return True
candidates = ["racecar", "A man, a plan, a canal: Panama!", "hello", ""]
for candidate in candidates:
print(f"{candidate!r} -> {is_palindrome(candidate)}")
print("half comparisons for racecar:", len("racecar") // 2)