这个Python代码在字符串中查找字符串的时间复杂度是多少

2024-06-09 22:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码在其他字符串中搜索字符串的时间和空间复杂度是多少,在查找时,函数应返回第一次出现的索引,否则为-1

我假设时间复杂度是O(m*n),其中m是草堆的长度,n是针的长度

然而,我搜索了python切片的内存复杂性,并在这里找到了这个答案-Time complexity of string slice,根据它是O(n^2)

那么,以下函数的总体时间和空间复杂度是多少

我们可以通过在干草堆上使用memoryview来改进它吗

class Solution:
  def strStr(self, haystack, needle):
    if haystack == needle or needle == "":
        return 0
    
    needle_len = len(needle)
    haystack_len = len(haystack)
    
    for i in range(0, haystack_len - needle_len + 1):
        if needle == haystack[i:i+needle_len]:
            return i
    
    return -1

Tags: 函数内存字符串代码lenreturnif时间