LeetCode 题解工作台
找出数组中的第一个回文字符串
给你一个字符串数组 words ,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 "" 。 回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串 。 示例 1: 输入: words = ["abc","car","ada",…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们遍历数组 `words`,对于每个字符串 `w`,判断其是否为回文字符串,如果是,则返回 `w`,否则继续遍历。 判断一个字符串是否为回文字符串,可以使用双指针,分别指向字符串的首尾,向中间移动,判断对应的字符是否相等。如果遍历完整个字符串,都没有发现不相等的字符,则该字符串为回文字符串。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串数组 words ,找出并返回数组中的 第一个回文字符串 。如果不存在满足要求的字符串,返回一个 空字符串 "" 。
回文字符串 的定义为:如果一个字符串正着读和反着读一样,那么该字符串就是一个 回文字符串 。
示例 1:
输入:words = ["abc","car","ada","racecar","cool"] 输出:"ada" 解释:第一个回文字符串是 "ada" 。 注意,"racecar" 也是回文字符串,但它不是第一个。
示例 2:
输入:words = ["notapalindrome","racecar"] 输出:"racecar" 解释:第一个也是唯一一个回文字符串是 "racecar" 。
示例 3:
输入:words = ["def","ghi"] 输出:"" 解释:不存在回文字符串,所以返回一个空字符串。
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]仅由小写英文字母组成
解题思路
方法一:模拟
我们遍历数组 words,对于每个字符串 w,判断其是否为回文字符串,如果是,则返回 w,否则继续遍历。
判断一个字符串是否为回文字符串,可以使用双指针,分别指向字符串的首尾,向中间移动,判断对应的字符是否相等。如果遍历完整个字符串,都没有发现不相等的字符,则该字符串为回文字符串。
时间复杂度 ,其中 为数组 words 中所有字符串的长度之和。空间复杂度 。
class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return next((w for w in words if w == w[::-1]), "")
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N \cdot M) |
| 空间 | O(1) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.