leetcode-pp / 91alg-13-daily-check

0 stars 0 forks source link

【Day 84 】2024-06-30 - 28 实现 strStr( #85

Open azl397985856 opened 4 days ago

azl397985856 commented 4 days ago

28 实现 strStr(

入选理由

暂无

题目地址

[ 之 KMP 篇)

https://leetcode-cn.com/problems/implement-strstr/]( 之 KMP 篇)

https://leetcode-cn.com/problems/implement-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() 定义相符。

lxy1108 commented 3 days ago
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        # return haystack.find(needle)
        for i in range(len(haystack)):
            flag = True
            for j in range(len(needle)):
                if i+j>=len(haystack) or needle[j]!=haystack[i+j]:
                    flag=False
                    break
            if flag:
                return i
        return -1
CathyShang commented 3 days ago

KMP实现,核心构建next数组记录前缀与后缀相等长度

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n, m = len(haystack), len(needle)
        if n<m: return -1
        # 有一个next记录,前缀和后缀
        def getNext(s):
            j = 0
            n = len(s)
            ans = [0]*n
            for i in range(1, n):
                while s[i] != s[j]:
                    if j > 0:
                        j = ans[j-1]
                    else:
                        ans[i]=0
                        break
                if s[i]==s[j]:
                    j += 1
                ans[i]=j
            return ans
        nexts = getNext(needle)
        i,j = 0,0
        while i<n and j < m:
            if haystack[i]==needle[j]:
                i+=1
                j+=1
            else:
                if j>0:
                    j = nexts[j-1]
                else:
                    i += 1
            if j==m:
                return i-j
        return -1
Dtjk commented 3 days ago

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

return haystack.find(needle)

    for i in range(len(haystack)):
        flag = True
        for j in range(len(needle)):
            if i+j>=len(haystack) or needle[j]!=haystack[i+j]:
                flag=False
                break
        if flag:
            return i
    return -1