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

这是字符串匹配问题,朴素做法是两重遍历,依次从主串的i位置开始查看是否和模式串匹配,若不匹配就换下一个位置进行判断,直到找到或者遍历完,时间复杂度 O ( m × n ) O(m \times n) O(m×n)

还可以对主串进行处理,把所有匹配模式串的字串替换为"1",然后在替换后的主串里面寻找第一个"1"出现的位置

但是这道题时间复杂度最低的还是得考虑用KMP算法,时间复杂度 O ( m + n ) O(m + n) O(m+n),这里我是看到Youtube上一位博主的讲解才恍然大悟的,链接在这里

python 复制代码
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle) == 0:
            return 0
        if len(needle) > len(haystack):
            return -1
        
        next = self.getNext(needle)
        j = 0
        for i in range(len(haystack)):
            while j > 0 and haystack[i] != needle[j]:
                j = next[j-1]
            if haystack[i] == needle[j]:
                j += 1
            if j == len(needle):
                return i - j + 1
        return -1

    def getNext(self, needle):
        next = [0] * len(needle)
        j = 0
        for i in range(1, len(needle)):
            while j > 0 and needle[j] != needle[i]:
                j = next[j-1]
            if needle[j] == needle[i]:
                j += 1
            next[i] = j
        return next

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        restr = haystack.replace(needle, '1')
        for i in range(len(restr)):
            if restr[i] == '1':
                return i
        return -1
相关推荐
豌豆花下猫3 分钟前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
爱研究的小陈3 分钟前
Day 3:数学基础回顾——线性代数与概率论在AI中的核心作用
算法
渭雨轻尘_学习计算机ing6 分钟前
二叉树的最大宽度计算
算法·面试
小杨4046 分钟前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪7 分钟前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi
船长@Quant9 分钟前
文档构建:Sphinx全面使用指南 — 进阶篇
python·markdown·sphinx·文档构建
cloudy49111 分钟前
强化学习:历史基金净产值,学习最大化长期收益
python·强化学习
Bruce_Liuxiaowei23 分钟前
使用Python脚本在Mac上彻底清除Chrome浏览历史:开发实战与隐私保护指南
chrome·python·macos
ruyingcai66666635 分钟前
用python进行OCR识别
开发语言·python·ocr
Niuguangshuo38 分钟前
Python设计模式:MVC模式
python·设计模式·mvc