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
相关推荐
Dlrb12113 小时前
C语言-指针三
c语言·算法·指针·const·命令行参数
Tisfy3 小时前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
IronMurphy3 小时前
【算法四十七】152. 乘积最大子数组
算法
2301_803934613 小时前
Go语言如何做网络爬虫_Go语言爬虫开发教程【指南】
jvm·数据库·python
WL_Aurora3 小时前
Python爬虫实战(六):新发地蔬菜价格数据采集.
爬虫·python
盲敲代码的阿豪3 小时前
Python 入门基础教程(爬虫前置版)
开发语言·爬虫·python
weixin199701080164 小时前
[特殊字符] 智能数据采集:数字化转型的“数据石油勘探队”(附Python实战源码)
开发语言·python
淘矿人4 小时前
Claude辅助DevOps实践
java·大数据·运维·人工智能·算法·bug·devops
Cosolar4 小时前
万字详解:RAG 向量索引算法与向量数据库架构及实战
数据库·人工智能·算法·数据库架构·milvus
次元工程师!5 小时前
LangFlow开发(三)—Bundles组件架构设计(3W+字详细讲解)
java·前端·python·低代码·langflow