Skip to content

28.找出字符串中第一个匹配项的下标

KMP, https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/

给你两个字符串 haystackneedle ,请你在 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 <= 104
  • haystackneedle 仅由小写英文字符组成

用KMP,而不是用find函数。

python
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        def kmp_next(s):	# 计算最长前缀后缀数组
            n = len(s)
            dp = [0] * n
            length = 0
            for fast in range(1, n):
                while length > 0 and s[fast] != s[length]:
                    length = dp[length - 1]
                if s[fast] == s[length]:
                    length += 1
                dp[fast] = length
            return dp
        
        next_ = kmp_next(needle)
        length = 0	# 模式串索引
        for fast in range(len(haystack)):	# 主串索引
            while length > 0 and haystack[fast] != needle[length]:
                length = next_[length - 1]
            if haystack[fast] == needle[length]:
                length += 1
            if length == len(needle):
                return fast - length + 1
        return -1