2024/12/16 【字符串】LeetCode28.找出字符串中第一个匹配项的下标/实现strStr()🌺🌺🌺 【❌】 知识点:KMP🌟🌟🌟,find函数,index函数

代码随想录

文本串,模式串 

前缀表,前缀(包含首字母,不包含尾字母的所有字串),后缀(包含尾字母,不包含首字母的所有字串)

最长相等前后缀

next数组/prefix数组

帮你把KMP算法学个通透!(理论篇)_哔哩哔哩_bilibili

解法1:利用KMP方法,前缀表(不减一)

class Solution:
    def getNext(self, next: list, t: str):
        j = 0
        next[0] = j
        for i in range(1, len(t)):
            while j > 0 and t[i] != t[j]:
                j = next[j-1]
            if t[i] == t[j]:
                j += 1
            next[i] = j

    def strStr(self, haystack: str, needle: str) -> int:
        m, n = len(haystack), len(needle)
        if n == 0:
            return 0
        j = 0
        next = [0]*n
        self.getNext(next, needle)
        for i in range(m):
            while j > 0 and haystack[i] != needle[j]:
                j = next[j-1]
            if haystack[i] == needle[j]:
                j += 1
            if j == n:
                return i-n+1     
        return -1  

解法2:前缀表(减一)

class Solution:
    def getNext(self, next: list, t: str):
        j = -1
        next[0] = j
        for i in range(1, len(t)):
            while j >= 0 and t[i] != t[j+1]:
                j = next[j]
            if t[i] == t[j+1]:
                j += 1
            next[i] = j

    def strStr(self, haystack: str, needle: str) -> int:
        m, n = len(haystack), len(needle)
        if n == 0:
            return 0
        j = -1
        next = [0]*n
        self.getNext(next, needle)
        for i in range(m):
            while j >= 0 and haystack[i] != needle[j+1]:
                j = next[j]
            if haystack[i] == needle[j+1]:
                j += 1
            if j == n-1:
                return i-n+1     
        return -1  

解法3:暴力解法

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

解法4:index函数

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        try:
            return haystack.index(needle)
        except ValueError:
            return -1

解法5:find函数

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

知识点:find函数和index函数

在 Python 中,字符串的 find() 方法用于在字符串中查找子字符串,并返回子字符串的第一个匹配位置的索引。如果子字符串不在字符串中,则返回 -1

语法

str.find(sub[, start[, end]])
  • sub:要查找的子字符串。
  • start(可选):开始查找的起始位置,默认为 0。
  • end(可选):结束查找的终止位置,默认为字符串的长度。

示例

使用 startend

text = "hello world, hello Python"
print(text.find("hello", 5))  # 从索引 5 开始查找,输出: 13
print(text.find("hello", 5, 10))  # 在索引 5 到 10 之间查找,输出: -1

index() 的区别

find()index() 功能类似,但当子字符串不存在时:

  • find() 返回 -1
  • index() 抛出 ValueError

示例:

text = "hello world"
print(text.find("Python"))  # 输出: -1
# print(text.index("Python"))  # 抛出 ValueError
posted on 2024-12-23 15:47  axuu  阅读(16)  评论(0)    收藏  举报