gpt4 book ai didi

python str.index 时间复杂度

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:43 29 4
gpt4 key购买 nike

为了找到子字符串在字符串中的位置,朴素算法将花费 O(n^2) 时间。然而,使用一些高效的算法(例如 KMP algorithm ),这可以在 O(n) 时间内实现:

s = 'saurabh'
w = 'au'

def get_table():
i = 0; j = 2
t = []
t.append(-1); t.append(0)
while i < len(w):
if w[i] == w[j-1]:
t.append(j+1)
j += 1
else:
t.append(0)
j = 0
i += 1
return t

def get_word():
t = get_table()
i = j = 0
while i+j < len(s):
if w[j] == s[i+j]:
if j == len(w) - 1:
return i
j += 1
else:
if t[j] > -1:
i = i + j - t[j]
j = t[j]
else:
i += 1
return -1

if __name__ == '__main__':
print get_word()

但是,如果我们这样做:'saurabh'.index('ra'),它是否在内部使用一些有效的算法在 O(n) 中计算它或者它使用复杂度 O(n^2) 的朴素算法 ?

最佳答案

在那篇文章 [1] 中,作者详细介绍了算法并对其进行了解释。来自文章:

The function “fastsearch” is called. It is a mix between 
Boyer-Moore and Horspool algorithms plus couple of neat tricks.

来自 Boyer–Moore–Horspool 算法 [2] 的 wiki 页面:

The algorithm trades space for time in order to obtain an 
average-case complexity of O(N) on random text, although
it has O(MN) in the worst case, where the length of the
pattern is M and the length of the search string is N.

希望对您有所帮助!

[1] http://www.laurentluce.com/posts/python-string-objects-implementation

[2] https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

关于python str.index 时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36868479/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com