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
相关推荐
MyY_DO6 分钟前
序列模型说人话
python
计算机安禾7 分钟前
【C语言程序设计】第38篇:链表数据结构(二):链表的插入与删除操作
c语言·开发语言·数据结构·c++·算法·链表
AC赳赳老秦7 分钟前
使用OpenClaw tavily-search技能高效撰写工作报告:以人工智能在医疗行业的应用为例
运维·人工智能·python·flask·自动化·deepseek·openclaw
颜酱7 分钟前
吃透回溯算法:从框架到实战
javascript·后端·算法
oem1109 分钟前
C++中的适配器模式
开发语言·c++·算法
jing-ya14 分钟前
day 57 图论part9
java·开发语言·数据结构·算法·图论
2401_8942419215 分钟前
C++与Rust交互编程
开发语言·c++·算法
啊我不会诶25 分钟前
Codeforces Round 1083 (Div. 2)vp补题
c++·学习·算法
未知鱼27 分钟前
Python安全开发之简易whois查询
java·python·安全
cpp_250127 分钟前
P1203 [IOI 1993 / USACO1.1] 坏掉的项链 Broken Necklace
数据结构·c++·算法·线性dp