LeetCode 题解工作台

找出数组中的第一个回文字符串

给你一个字符串数组 words ,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 "" 。 回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串 。 示例 1: 输入: words = ["abc","car","ada",…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们遍历数组 `words`,对于每个字符串 `w`,判断其是否为回文字符串,如果是,则返回 `w`,否则继续遍历。 判断一个字符串是否为回文字符串,可以使用双指针,分别指向字符串的首尾,向中间移动,判断对应的字符是否相等。如果遍历完整个字符串,都没有发现不相等的字符,则该字符串为回文字符串。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words ,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 ""

回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串

 

示例 1:

输入:words = ["abc","car","ada","racecar","cool"]
输出:"ada"
解释:第一个回文字符串是 "ada" 。
注意,"racecar" 也是回文字符串,但它不是第一个。

示例 2:

输入:words = ["notapalindrome","racecar"]
输出:"racecar"
解释:第一个也是唯一一个回文字符串是 "racecar" 。

示例 3:

输入:words = ["def","ghi"]
输出:""
解释:不存在回文字符串,所以返回一个空字符串。

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 仅由小写英文字母组成
lightbulb

解题思路

方法一:模拟

我们遍历数组 words,对于每个字符串 w,判断其是否为回文字符串,如果是,则返回 w,否则继续遍历。

判断一个字符串是否为回文字符串,可以使用双指针,分别指向字符串的首尾,向中间移动,判断对应的字符是否相等。如果遍历完整个字符串,都没有发现不相等的字符,则该字符串为回文字符串。

时间复杂度 O(L)O(L),其中 LL 为数组 words 中所有字符串的长度之和。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        return next((w for w in words if w == w[::-1]), "")
speed

复杂度分析

指标
时间O(N \cdot M)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for efficient handling of string iteration.

  • question_mark

    Ensure the candidate applies the two-pointer technique correctly.

  • question_mark

    Check if the solution returns early upon finding the first palindromic word.

warning

常见陷阱

外企场景
  • error

    Failing to iterate through the array properly.

  • error

    Not returning early when the first palindromic word is found.

  • error

    Incorrectly assuming that checking palindromic status is trivial without using a systematic approach like two-pointer scanning.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the first palindrome with specific character conditions (e.g., only vowels).

  • arrow_right_alt

    Handle larger inputs efficiently with O(N * M) time complexity.

  • arrow_right_alt

    Extend to find the longest palindromic string in the array.

help

常见问题

外企场景

找出数组中的第一个回文字符串题解:双·指针·invariant | LeetCode #2108 简单