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
相关推荐
POLITE323 分钟前
Leetcode 42.接雨水 JavaScript (Day 3)
javascript·算法·leetcode
Tim_1024 分钟前
【算法专题训练】36、前缀树路径和
算法
好易学·数据结构29 分钟前
可视化图解算法76:最大子数组和
数据结构·算法·leetcode·面试·动态规划·力扣·笔试
tang7778931 分钟前
Python爬虫代理,选短效IP还是长效IP?
爬虫·python·tcp/ip
写文章的大米1 小时前
这份数据验证方案,可以让你的 FastAPI 崩溃率直降90%
python
副露のmagic1 小时前
更弱智的算法学习 day13
学习·算法
xingzhemengyou11 小时前
Python 有哪些定时器
前端·python
站大爷IP1 小时前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
python
BBB努力学习程序设计1 小时前
Python 高效处理大数据:生成器(Generator)的工作机制与实战技巧
python
青岛少儿编程-王老师1 小时前
CCF编程能力等级认证GESP—C++1级—20251227
java·c++·算法