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
相关推荐
Cha0DD2 小时前
【由浅入深探究langchain】第二十集-SQL Agent+Human-in-the-loop
人工智能·python·ai·langchain
Cha0DD2 小时前
【由浅入深探究langchain】第十九集-官方的SQL Agent示例
人工智能·python·ai·langchain
阿豪学编程3 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
智算菩萨4 小时前
【Tkinter】4 Tkinter Entry 输入框控件深度解析:数据验证、密码输入与现代表单设计实战
python·ui·tkinter·数据验证·entry·输入框
墨韵流芳4 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
七夜zippoe4 小时前
可解释AI:构建可信的机器学习系统——反事实解释与概念激活实战
人工智能·python·机器学习·可解释性·概念激活
csdn_aspnet4 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼5 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒5 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
paeamecium6 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试