LeetCode 题解工作台
找出字符串中第一个匹配项的下标
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。 示例 1: 输入: haystack = "sadbutsad", ne…
3
题型
9
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
以字符串 `haystack` 的每一个字符为起点与字符串 `needle` 进行比较,若发现能够匹配的索引,直接返回即可。 假设字符串 `haystack` 长度为 ,字符串 `needle` 长度为 ,则时间复杂度为 $O((n-m) \times m)$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104haystack和needle仅由小写英文字符组成
解题思路
方法一:遍历
以字符串 haystack 的每一个字符为起点与字符串 needle 进行比较,若发现能够匹配的索引,直接返回即可。
假设字符串 haystack 长度为 ,字符串 needle 长度为 ,则时间复杂度为 ,空间复杂度 。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
for i in range(n - m + 1):
if haystack[i : i + m] == needle:
return i
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O((N-M+1)*M) in the worst case for a naive two-pointer scan, where N is haystack length and M is needle length. Space complexity is O(1) extra for pointer tracking; no additional data structures are required. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checking if candidate matches incrementally rather than full substring comparisons.
- question_mark
Asking about worst-case behavior when haystack contains repeated partial matches of needle.
- question_mark
Interest in whether early termination is implemented to optimize sequential scans.
常见陷阱
外企场景- error
Resetting both pointers incorrectly on mismatch, skipping potential matches.
- error
Assuming needle appears and not handling the -1 return properly.
- error
Confusing substring lengths and causing index out-of-bounds errors during scanning.
进阶变体
外企场景- arrow_right_alt
Return all indices where needle occurs instead of just the first.
- arrow_right_alt
Allow wildcard characters in needle during matching.
- arrow_right_alt
Implement using KMP or Rabin-Karp for improved time complexity.