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
相关推荐
Thneonl38 分钟前
Celery 生产踩坑:1000 任务积压与 acks_late 双重执行
后端·python
清桔38 分钟前
模型的调用
python
小小张说故事38 分钟前
Python 多线程为什么跑不快?asyncio 入门指南:异步并发从零上手
后端·python
10年前端老司机39 分钟前
干货分享|企业智能知识库 Rerank 重排序落地实践与踩坑总结
python·aigc·agent
用户9799848071839 分钟前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks40 分钟前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
天天被压力1 小时前
【Python 量化取数指南 #13】Python 把行情落库:sqlite 一键存,回测随用随取
java·人工智能·python
天天被压力1 小时前
【Python 量化取数指南 #14】Python 清洗行情数据:复权停牌对齐,回测不翻车
java·人工智能·python
Python私教1 小时前
Python环境配置:conda+PyCharm+换源,附6个坑
人工智能·python·pycharm
databook1 小时前
检测数据异常值的五种统计技术
python·数据挖掘·数据分析