Leetcode| 28. 实现 strStr()、459.重复的子字符串 Day9

28. Find the Index of the First Occurrence in a String

Python find()

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)

朴素解法

遍历,haystack中每个字母作为发起点

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(len(haystack) - len(needle) +1):
            if haystack[i: i+len(needle)] == needle:
                return i
        return -1

KMP

YouTube上这个视频讲得很清楚
意思明白,代码难写
。。。

# 2023年8月3日
# https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/2335848/javapython3wei-shi-yao-shi-kmptu-jie-by-p2d4b/
class Solution:
    def getNext(self, next, needle):
        for i in range(1, len(needle)):
            k = next[i - 1]
            while needle[i] != needle[k]:
                if k == 0:
                    k -= 1  # 为了和最后的next[i] = k + 1匹配
                    break
                else:
                    k = next[k - 1]
        
            next[i] = k + 1

    def strStr(self, haystack: str, needle: str) -> int:
        next = [0] * len(needle)
        self.getNext(next, needle)
        i = 0   # 遍历haystack
        j = 0   # 遍历needle
        while i < len(haystack):
            if haystack[i] == needle[j]:
                i += 1
                j += 1
            elif j == 0:
                i += 1  # needle第一个字符就开始不匹配
            else:
                j = next[j - 1]
            if j >= len(needle):
                return i - len(needle)

        return -1


459. Repeated Substring Pattern

假设字符串S可以被它的字串Sp多次重复构成,那么可以表示为S = SpSp
若将两个S拼接,则SS = SpSpSpSp.
通过去除SS首尾的两个字符,可以得新的SS2 = SxSpSpSy.
SS2中应包含S.

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        t = s + s
        if t.find(s, 1, len(t)-1) != -1:
            return True
        else:
            return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值