LeetCode 题解工作台

验证回文串

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。 字母和数字都属于字母数字字符。 给你一个字符串 s ,如果它是 回文串 ,返回 true ;否则,返回 false 。 示例 1: 输入: s = "A man, a pl…

category

2

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们用双指针 和 分别指向字符串 的两端,接下来循环以下过程,直至 $i \geq j$: 1. 如果 不是字母或数字,指针 右移一位,继续下一次循环;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串

字母和数字都属于字母数字字符。

给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false

 

示例 1:

输入: s = "A man, a plan, a canal: Panama"
输出:true
解释:"amanaplanacanalpanama" 是回文串。

示例 2:

输入:s = "race a car"
输出:false
解释:"raceacar" 不是回文串。

示例 3:

输入:s = " "
输出:true
解释:在移除非字母数字字符之后,s 是一个空字符串 "" 。
由于空字符串正着反着读都一样,所以是回文串。

 

提示:

  • 1 <= s.length <= 2 * 105
  • s 仅由可打印的 ASCII 字符组成
lightbulb

解题思路

方法一:双指针

我们用双指针 iijj 分别指向字符串 ss 的两端,接下来循环以下过程,直至 iji \geq j

  1. 如果 s[i]s[i] 不是字母或数字,指针 ii 右移一位,继续下一次循环;
  2. 如果 s[j]s[j] 不是字母或数字,指针 jj 左移一位,继续下一次循环;
  3. 如果 s[i]s[i]s[j]s[j] 的小写形式不相等,返回 false
  4. 否则,指针 ii 右移一位,指针 jj 左移一位,继续下一次循环。

循环结束,返回 true

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def isPalindrome(self, s: str) -> bool:
        i, j = 0, len(s) - 1
        while i < j:
            if not s[i].isalnum():
                i += 1
            elif not s[j].isalnum():
                j -= 1
            elif s[i].lower() != s[j].lower():
                return False
            else:
                i, j = i + 1, j - 1
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Evaluate the candidate’s ability to implement two-pointer techniques.

  • question_mark

    Check if the candidate effectively handles edge cases such as empty strings or strings with non-alphanumeric characters.

  • question_mark

    Observe the candidate's ability to optimize both time and space for this problem.

warning

常见陷阱

外企场景
  • error

    Forgetting to ignore non-alphanumeric characters, which can lead to incorrect results.

  • error

    Not converting all characters to lowercase, causing mismatches between uppercase and lowercase letters.

  • error

    Not handling the empty string or edge cases where the string is very short.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Palindromes with mixed case and special characters.

  • arrow_right_alt

    Strings with a large number of non-alphanumeric characters.

  • arrow_right_alt

    Edge case handling for strings of length 1 or 0.

help

常见问题

外企场景

验证回文串题解:双·指针·invariant | LeetCode #125 简单