← 中文资源

简体中文版本

双指针回文判定

两个指针从两端向中间收拢:非字母数字字符直接跳过、字母统一转小写再比较,一轮只需一半比较次数;带标点的长句也能判回文,空串视为回文。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

'racecar' -> True
'A man, a plan, a canal: Panama!' -> True
'hello' -> False
'' -> True
half comparisons for racecar: 3

实现说明

双指针回文判定以函数 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)