代码随想录打卡d9:KMP算法

实现strStr()

刷题日期:2024-04-25
[[028. 实现 strStr()]]

思路

KMP算法

算法思路

先计算前缀表, 再逐个匹配

算法细节

1. 计算前缀表和匹配过程中匹配失败

失败要一直往前走

Code

class Solution:
    def cal_pre(self, strs):
        prefix = [0] * len(strs)
        i = 0
        j = 1
        while j < len(strs):
            if strs[i] != strs[j]:
                while i > 0 and strs[i] != strs[j]:
                    i = prefix[i - 1]
            if strs[i] == strs[j]:
                prefix[j] = 1 + i
                i += 1
            j += 1
        return prefix
    def strStr(self, haystack: str, needle: str) -> int:
        prefix = self.cal_pre(needle)
        j = 0
        for i in range(len(haystack)):
            while haystack[i] != needle[j] and j > 0:
                j = prefix[j - 1]
            if haystack[i] == needle[j]:
                j += 1
            if j == len(needle):
                return i - j + 1
        return -1

重复的子字符串

刷题日期:2024-04-25
[[459.重复的子字符串]]

思路

KMP算法

算法思路

通过计算前缀表可知, 如果字符串可以由字串构成, 那么前缀表最后一位不为0, 并且前缀表最后一位的值是前缀表中0的数量的整数倍

算法细节

1.

Code

class Solution:
    def cal_pre(self, strs):
        prefix = [0] * len(strs)
        i = 0
        j = 1
        while j < len(strs):
            if strs[i] != strs[j]:
                while i > 0 and strs[i] != strs[j]:
                    i = prefix[i - 1]
            if strs[i] == strs[j]:
                prefix[j] = 1 + i
                i += 1
            j += 1
        return prefix
    def repeatedSubstringPattern(self, s: str) -> bool:
        prefix = self.cal_pre(s)
        if prefix[-1] == 0:
            return False
        temp = len(s) - prefix[-1]

        if prefix[-1] % temp == 0:
            return True
        else:
            return False
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值