(※)力扣刷题-字符串-实现 strStr()(KMP算法)

28 实现 strStr()

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2

示例 2: 输入: haystack = "aaaaa", needle = "bba" 输出: -1

说明: **当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 对于本题而言,当 needle 是空字符串时我们应当返回 0 **。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

思路

首先是模式串匹配问题,需要先在hatstack(文本串)中找到needle子串(模式串),然后再去考虑求这个索引。第一个问题就涉及到KMP算法。KMP的经典思想就是:当出现字符串不匹配时,可以记录一部分之前已经匹配的文本内容,利用这些信息避免从头再去做匹配。

以下代码随想录文字详细说明了KMP算法:
https://www.programmercarl.com/0028.实现strStr.html#思路

解法一-前缀表(减一)

python 复制代码
class Solution(object):
    # 第一步 首先要求next数组
    def getNext(self, next, s): # s表示模式串
        # 初始化
        j = -1
        next[0] = j
        for i in range(1, len(s)): # 注意i从1开始 因为要比较 i 和 j是否相同
            # 前后缀不相同 
            while j>=0 and s[i]!=s[j+1]:
                j = next[j] # j回退
            # 前后缀相同
            if s[i]==s[j+1]:
                j += 1 # i和j都加1
            next[i] = j

    # 第二步 求下标索引
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        next = [0]*len(needle) # 初始化next
        self.getNext(next, needle)
        j = -1
        for i in range(len(haystack)):
            while j >= 0 and haystack[i]!=needle[j+1]: # j+1是因为j初始值为-1
                j = next[j] # next数组起作用了 找下一个匹配的位置
            if haystack[i]==needle[j+1]: # 匹配到字符相同
                j += 1
            # 判断在文本串里出现了模式串
            if j == len(needle) - 1:
                return i - len(needle) + 1 # 返回索引
        return -1

暴力法

python 复制代码
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        m, n = len(haystack), len(needle)
        for i in range(m):
            if haystack[i:i+n] == needle:
                return i
        return -1   

使用index(写算法题不推荐)

python 复制代码
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        try:
            return haystack.index(needle)
        except ValueError:
            return -1

使用find(写算法题不推荐)

python 复制代码
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)
相关推荐
Geoking.10 分钟前
PyTorch 中 model.eval() 的使用与作用详解
人工智能·pytorch·python
nn在炼金10 分钟前
图模式分析:PyTorch Compile组件解析
人工智能·pytorch·python
执笔论英雄11 分钟前
【大模型训练】zero2 梯度分片
pytorch·python·深度学习
Danceful_YJ13 分钟前
25.样式迁移
人工智能·python·深度学习
烛阴17 分钟前
Python 几行代码,让你的照片秒变艺术素描画
前端·python
喆星时瑜17 分钟前
关于 ComfyUI 的 Windows 本地部署系统环境教程(详细讲解Windows 10/11、NVIDIA GPU、Python、PyTorch环境等)
python·cuda·comfyui
柳鲲鹏22 分钟前
RGB转换为NV12,查表式算法
linux·c语言·算法
橘颂TA22 分钟前
【剑斩OFFER】算法的暴力美学——串联所有单词的字串
数据结构·算法·c/c++
Kuo-Teng23 分钟前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展