【发布时间】:2016-08-20 11:47:31
【问题描述】:
为了在字符串中查找子字符串的位置,一个简单的算法将花费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)?
【问题讨论】:
-
你可以分析它,看看时间是指数增长还是线性增长;)
标签: python algorithm time-complexity string-algorithm