返回题库|

KMP算法

中等美团

KMP算法

中等美团字符串

题目描述

实现 strStr() 函数:给定一个 haystack 字符串和一个 needle 字符串,在 haystack 中找出 needle 字符串出现的第一个位置的索引。如果 needle 不是 haystack 的一部分,则返回 -1。使用 KMP 算法通过构建部分匹配表(failure function)来避免不必要的回溯,将时间复杂度优化到 O(n+m)。

示例

输入:haystack = "hello", needle = "ll"
输出:2
solution.ts
输出结果
点击「运行代码」按钮查看结果...