LeetCode-子串匹配——D12【一般难度】

题目描述

实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:

输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:

输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

算法思路

可以利用python中的find函数实现(简单)
也可以使用KMP算法实现(一般难度)

算法实现

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle not in haystack:
            return -1
        else:
            a = haystack.find(needle)
            return a
#实现KMP算法
class KMP():
    #kmp算法框架
    def kmp(self,string, substring):
        pnext = self.getNext(substring)
        print("next数组为:",pnext)
        n = len(string)
        m = len(substring)
        i, j = 0, 0
        while (i<n) and (j<m):#迭代匹配 
            if (string[i]==substring[j]):
                i += 1
                j += 1
            elif (j!=0):
                #在迭代中,如果此次没有成功匹配,则下一次从pnext[j-1]中存储的元素开始索引
                j = pnext[j-1]
            else:
                #如果j=0,表示主串向前移动一个继续匹配子串
                i += 1
        
        if (j == m):#匹配成功
            return i-j
        else:#匹配失败
            return -1
        
    #求子串next数组
    def getNext(self,substring):
        index, m = 0, len(substring)#index为子串索引,m为子串长度
        pnext = [0]*m#next数组
        i = 1
        while i<m:
            #打印next数组生成过程
            print("i=%d,next=%s"%(i,pnext))
            #index和i中所指元素相同,则next数组对应位置加1
            if (substring[i] == substring[index]):
                pnext[i] = index + 1
                index += 1
                i += 1
            elif index!=0:
                index = pnext[index-1]
            else:
                pnext[i] = 0
                i += 1
        return pnext
                
test=Solution()
print(test.strStr("abcxabcdabcdabcy","abcdabcy"))
kmp=KMP()
print(kmp.kmp("abcxabcdabcdabcy","abcdabcy"))

最终结果截图为:
在这里插入图片描述

更多kmp相关知识请看我之前的一篇博客:
https://blog.csdn.net/qq_33414271/article/details/83789478

发布了205 篇原创文章 · 获赞 655 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/qq_33414271/article/details/99245292
D12