LeetCode 28. 实现 strStr()

28. 实现 strStr()

题目:
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

链接 https://leetcode.cn/problems/implement-strstr/

个人思路
  1. python find 方法
    首先判断needle字符串长度是否为0,是则直接返回0,否则使用find方法即可

  2. 但一味使用python自带方法那刷题则毫无意义且不利于笔试面试,这里尝试自己暴力解法

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if len(needle) == 0:
            return 0
        else:
            for i in range(len(haystack)):
                if len(haystack)-i < len(needle):
                    return -1
                if haystack[i] == needle[0]:
                    # 本来不想从0开始,但就要增加一个字符串长度为1的判断
                    for j in range(0,len(needle)):
                       # 对比接下来needle的每个字符是否和haystack接下来的字符一致
                        if needle[j] != haystack[i+j]:
                            break
                         # 如果needle能在haystack中找到,则返回下标
                        elif j == len(needle)-1:
                           return i
            return -1
复杂度分析

时间复杂度:略
空间复杂度:略

其他思路
  1. 暴力解法
    让字符串needle 与字符串 haystack 的所有长度为 mm 的子串均匹配一次
    时间复杂度: O(n×m),其中 nn 是字符串 ,haystack 的长度,mm 是字符串needle 的长度。最坏情况下我们需要将字符串needle 与字符串haystack 的所有长度为 mm 的子串均匹配一次。

空间复杂度:O(1)。我们只需要常数的空间保存若干变量。

  1. KMP算法
    具体可以参照下面链接:
    知乎:https://www.zhihu.com/question/21923021/answer/281346746
    LeetCode:https://leetcode.cn/problems/implement-strstr/solution/shua-chuan-lc-shuang-bai-po-su-jie-fa-km-tb86/
    LeetCode:https://leetcode.cn/problems/implement-strstr/solution/dai-ma-sui-xiang-lu-kmpsuan-fa-xiang-jie-mfbs/
// 方法一
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        a=len(needle)
        b=len(haystack)
        if a==0:
            return 0
        next=self.getnext(a,needle)
        p=-1
        for j in range(b):
            while p>=0 and needle[p+1]!=haystack[j]:
                p=next[p]
            if needle[p+1]==haystack[j]:
                p+=1
            if p==a-1:
                return j-a+1
        return -1

    def getnext(self,a,needle):
        next=['' for i in range(a)]
        k=-1
        next[0]=k
        for i in range(1,len(needle)):
            while (k>-1 and needle[k+1]!=needle[i]):
                k=next[k]
            if needle[k+1]==needle[i]:
                k+=1
            next[i]=k
        return next
  1. Sunday 算法

Sunday 匹配机制

目标字符串String

模式串 Pattern

当前查询索引 idx (初始为 00)

待匹配字符串 str_cut : String [ idx : idx + len(Pattern) ]

每次匹配都会从 目标字符串中 提取 待匹配字符串与 模式串 进行匹配:

若匹配,则返回当前 idx

不匹配,则查看 待匹配字符串 的后一位字符 c:

若c存在于Pattern中,则 idx = idx + 偏移表[c]

否则,idx = idx + len(pattern)

Repeat Loop 直到 idx + len(pattern) > len(String)
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
    
        # Func: 计算偏移表
        def calShiftMat(st):
            dic = {}
            for i in range(len(st)-1,-1,-1):
                if not dic.get(st[i]):
                    dic[st[i]] = len(st)-i
            dic["ot"] = len(st)+1
            return dic
        
        # 其他情况判断
        if len(needle) > len(haystack):return -1
        if needle=="": return 0
       
        # 偏移表预处理    
        dic = calShiftMat(needle)
        idx = 0
    
        while idx+len(needle) <= len(haystack):
            
            # 待匹配字符串
            str_cut = haystack[idx:idx+len(needle)]
            
            # 判断是否匹配
            if str_cut==needle:
                return idx
            else:
                # 边界处理
                if idx+len(needle) >= len(haystack):
                    return -1
                # 不匹配情况下,根据下一个字符的偏移,移动idx
                cur_c = haystack[idx+len(needle)]
                if dic.get(cur_c):
                    idx += dic[cur_c]
                else:
                    idx += dic["ot"]
            
        
        return -1 if idx+len(needle) >= len(haystack) else idx

作者:Tes
链接:https://leetcode.cn/problems/implement-strstr/solution/python3-sundayjie-fa-9996-by-tes/
来源:力扣(LeetCode)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值